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
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
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)
+++
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
.