I'm writing a function to replace every n-th letter from a string
def replaceN(str, n):
for i in range(len(str)):
n=str[i]
newStr=str.replace(n, "*")
return newStr
but when i execute it, only the first letter is replaced with a *. I'm sure there is a mistake, but i can't see it.
One-liner:
newstring = ''.join("*" if i % n == 0 else char for i, char in enumerate(string, 1))
Expanded:
def replace_n(string, n, first=0):
letters = (
# i % n == 0 means this letter should be replaced
"*" if i % n == 0 else char
# iterate index/value pairs
for i, char in enumerate(string, -first)
)
return ''.join(letters)
>>> replace_n("hello world", 4)
'*ell* wo*ld'
>>> replace_n("hello world", 4, first=-1)
'hel*o w*orl*'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With