Replace every nth letter in a string

后端 未结 7 819
渐次进展
渐次进展 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 04:00

    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.

提交回复
热议问题