Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace every nth letter in a string

Tags:

python

replace

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.

like image 896
trek Avatar asked Dec 02 '12 11:12

trek


1 Answers

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*'
like image 169
Eric Avatar answered Sep 17 '22 23:09

Eric