Replace nth occurrence of substring in string

后端 未结 10 2392
面向向阳花
面向向阳花 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条回答
  •  猫巷女王i
    2020-11-27 07:34

    You can use a while loop with str.find to find the nth occurrence if it exists and use that position to create the new string:

    def nth_repl(s, sub, repl, n):
        find = s.find(sub)
        # If find is not -1 we have found at least one match for the substring
        i = find != -1
        # loop util we find the nth or we find no match
        while find != -1 and i != n:
            # find + 1 means we start searching from after the last match
            find = s.find(sub, find + 1)
            i += 1
        # If i is equal to n we found nth match so replace
        if i == n:
            return s[:find] + repl + s[find+len(sub):]
        return s
    

    Example:

    In [14]: s = "foobarfoofoobarbar"
    
    In [15]: nth_repl(s, "bar","replaced",3)
    Out[15]: 'foobarfoofoobarreplaced'
    
    In [16]: nth_repl(s, "foo","replaced",3)
    Out[16]: 'foobarfooreplacedbarbar'
    
    In [17]: nth_repl(s, "foo","replaced",5)
    Out[17]: 'foobarfoofoobarbar'
    

提交回复
热议问题