Replace nth occurrence of substring in string

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

    Elegant and short:

    def replace_ocurrance(string,from,to,num)
         strange_char = “$&$@$$&”
         return string.replace(from,strange_char,num).replace(strange_char, from,num-1).replace(to, strange_char,1)
    

提交回复
热议问题