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(
Your code has several problems:
First, the return
in the wrong place. It is inside the for loop but it should be outside.
Next, in the following fragment:
for i in range(len(str)):
n=str[i]
newStr=str.replace(n, "*")
the n
that you passed as the second argument to your function is being overwritten at every loop step. So if your initial string is "abcabcabcd" and you pass n=3 (a number) as a second argument what your loop does is:
n="a"
n="b"
n="c"
...
so the value 3 is never used. In addition, in your loop only the last replacement done in your string is saved:
n="a"
newStr="abcabcabcd".replace("a", "*") --> newStr = "*bc*bc*bcd"
n="b"
newStr="abcabcabcd".replace("b", "*") --> newStr = "a*ca*ca*cd"
...
n="d"
newStr="abcabcabcd".replace("d", "*") --> newStr = "abcabcabc*"
If you test your function (after fixing the return
position) with some strings it seems to work fine:
In [7]: replaceN("abcabcabc", 3)
Out[7]: 'ab*ab*ab*'
but if you do the choice more carefully:
In [10]: replaceN("abcabcabcd", 3)
Out[10]: 'abcabcabc*'
then it is obvious that the code fails and it is equivalent to replace only the last character of your string:
my_string.replace(my_string[-1], "*")
The code given by Eric is working fine:
In [16]: ''.join("*" if i % 3 == 0 else char for i, char in enumerate("abcabcabcd"))
Out[16]: '*bc*bc*bc*'
It replaces positions 3rd, 6th, 9th and so on. It may need some adjustment if you don't want the position 0 being replaced too.