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(
I like Eric's answer, but you indicated in the comment that the first letter shouldn't be replaced. You can adapt the code like this then:
''.join("*" if i % n == 0 else char for i, char in enumerate(string, 1))
the difference is here ^
def replaceN(s, n):
return ''.join(
'*' if not i%n else char for i, char in enumerate(s, 1))
>>> replaceN('welcome', 3)
'we*co*e'
Try this:
def replaceN(string, n):
s = ''
for i in range(len(string)):
if i%n!=0:
s += string[i]
else:
s += '*'
return s
A simple way by redefining string every time:
def replaceN(string, n):
for i in range(n, len(string), n):
string = string[:i-1] + "*" + string[i:]
return string
In [1]: replaceN("abcabcabc", 3)
Out[1]: ab*ab*ab*
In [2]: replaceN("abcd abcd abcd", 4)
Out[2]: abcd*abcd*abcd
You've put your return within the loop so after the first iteration it returns the string without the rest of the string being replaced. The string should be returned once the loop has completely finished. Something like this should work:
def replaceN(str, n):
for i in range(len(str)):
n=str[i]
newStr=str.replace(n, "*")
return newStr
Another option, using re:
import re
def repl(matchobj):
return re.sub('.$','*',matchobj.group(0))
def replaceN(str, n):
return re.sub('.'*n,repl,str)
However, this needs additional library. If you have this library already imported, this may be a shorthand method.
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*'