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
  • 26,475
  • 20
  • 67
  • 118
reshmi g
  • 141
  • 4
  • 8
  • 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
  • 58,805
  • 11
  • 114
  • 143
  • 1
    Nice answer! I'd just make `n = min(len(string), n)` to ensure you don't return something bigger than it was. – H.D. Aug 31 '13 at 05:43
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
  • 42,176
  • 24
  • 124
  • 155