Replace nth occurrence of substring in string

后端 未结 10 2406
面向向阳花
面向向阳花 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:28

    The last answer is nearly perfect - only one correction:

        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)
            newString = before + after
            return newString
    

    The after-string has to be stored in the this variable again after replacement. Thank you for the great solution!

提交回复
热议问题