0

How can I perform this in Python?

strnset(string,symbol,n);

Output should be:

Enter String : ABCDEFGHIJ
Enter Symbol for replacement : +
How many string characters to be replaced : 4

Before strnset() : ABCDEFGHIJ
After strnset() : ++++EFGHIJ
Santosh Kumar
  • 24,301
  • 18
  • 65
  • 110
reshmi g
  • 141
  • 4
  • 7
  • 1
    Technically you can't, since strings in Python are immutable. – Ignacio Vazquez-Abrams Aug 31 '13 at 05:41
  • 5
    Seriously? You're asking this even after the responses you got for your [`strncpy` question](http://stackoverflow.com/questions/18535563/is-there-any-strncpy-equivalent-function-in-python)? – John Y Aug 31 '13 at 05:51

2 Answers2

6

You'll want to use Python's Slice Notation:

>>> def strnset(mystring, symbol, n):
...     return symbol*n + mystring[n:]
... 
>>> print strnset("ABCDEFGHIJ", "+", 4)
++++EFGHIJ

mystring[n:] gets every character after the nth character in the string. Then you can simply join it together with the signs.

Note, if you don't want a string returned which has more characters than the string you actually passed (eg, strnset('hi', '+', 4) == '++++'), then add this before the return statement:

n = min(len(mystring), n)

Now, when running:

>>> print strnset("HAI", "+", 4)
+++
Community
  • 1
  • 1
TerryA
  • 56,204
  • 11
  • 116
  • 135
0

Here's one with a generator expression:

chars = "ABCDEJGHIJ" 
r = "+" 
n = 4 
masked_result = "".join(r if idx <= n else c for idx, c in enumerate(chars, 1))

>>> '++++EJGHIJ'

Note: this supports masking values less than n.

monkut
  • 39,454
  • 22
  • 115
  • 146