Replace nth occurrence of substring in string

后端 未结 10 2363
面向向阳花
面向向阳花 2020-11-27 06:51

I want to replace the n\'th occurrence of a substring in a string.

There\'s got to be something equivalent to what I WANT to do which is

mystring.repl

10条回答
  •  春和景丽
    2020-11-27 07:23

    I use simple function, which lists all occurrences, picks the nth one's position and uses it to split original string into two substrings. Then it replaces first occurrence in the second substring and joins substrings back into the new string:

    import re
    
    def replacenth(string, sub, wanted, n):
        where = [m.start() for m in re.finditer(sub, string)][n-1]
        before = string[:where]
        after = string[where:]
        after = after.replace(sub, wanted, 1)
        newString = before + after
        print(newString)
    

    For these variables:

    string = 'ababababababababab'
    sub = 'ab'
    wanted = 'CD'
    n = 5
    

    outputs:

    ababababCDabababab
    

    Notes:

    The where variable actually is a list of matches' positions, where you pick up the nth one. But list item index starts with 0 usually, not with 1. Therefore there is a n-1 index and n variable is the actual nth substring. My example finds 5th string. If you use n index and want to find 5th position, you'll need n to be 4. Which you use usually depends on the function, which generates our n.

    This should be the simplest way, but maybe it isn't the most Pythonic way, because the where variable construction needs importing re library. Maybe somebody will find even more Pythonic way.

    Sources and some links in addition:

    • where construction: How to find all occurrences of a substring?
    • string splitting: https://www.daniweb.com/programming/software-development/threads/452362/replace-nth-occurrence-of-any-sub-string-in-a-string
    • similar question: Find the nth occurrence of substring in a string

提交回复
热议问题