Replace every nth letter in a string

后端 未结 7 870
渐次进展
渐次进展 2021-01-19 03:40

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(         


        
7条回答
  •  無奈伤痛
    2021-01-19 03:46

    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'
    

提交回复
热议问题