Replace every nth letter in a string

后端 未结 7 817
渐次进展
渐次进展 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'
    
    0 讨论(0)
  • 2021-01-19 03:53

    Try this:

    def replaceN(string, n):
        s = ''
        for i in range(len(string)):
            if i%n!=0:
                s += string[i]
            else:
                s += '*'
        return s
    
    0 讨论(0)
  • 2021-01-19 03:58

    A simple way by redefining string every time:

    def replaceN(string, n):
        for i in range(n, len(string), n):
            string = string[:i-1] + "*" + string[i:]
        return string
    
    
    In [1]: replaceN("abcabcabc", 3)
    Out[1]: ab*ab*ab*
    In [2]: replaceN("abcd abcd abcd", 4)
    Out[2]: abcd*abcd*abcd
    
    0 讨论(0)
  • 2021-01-19 04:00

    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:

    def replaceN(str, n):
        for i in range(len(str)):
            n=str[i]
            newStr=str.replace(n, "*")
        return newStr
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-19 04:02

    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*'
    
    0 讨论(0)
提交回复
热议问题