Skip to content Skip to sidebar Skip to footer

Replace Every Nth Letter In A String

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 newS

Solution 1:

One-liner:

newstring = ''.join("*"if i % n == 0elsecharfor i, charinenumerate(string, 1))

Expanded:

def replace_n(string, n, first=0):
    letters = (
        # i % n == 0 means this letter should be replaced"*"if i % n == 0elsechar# iterate index/value pairsfor i, charinenumerate(string, -first)
    )
    return ''.join(letters)
>>> replace_n("hello world", 4)
'*ell* wo*ld'>>> replace_n("hello world", 4, first=-1)
'hel*o w*orl*'

Solution 2:

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 inrange(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==0elsecharfor i, charin 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.

Solution 3:

Try this:

def replaceN(string, n):
    s = ''for i inrange(len(string)):
        if i%n!=0:
            s += string[i]
        else:
            s += '*'return s

Solution 4:

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:

defreplaceN(str, n):
    for i inrange(len(str)):
        n=str[i]
        newStr=str.replace(n, "*")
    return newStr

Solution 5:

Another option, using re:

import re
defrepl(matchobj):
    return re.sub('.$','*',matchobj.group(0))
defreplaceN(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.

Post a Comment for "Replace Every Nth Letter In A String"