Replace nth occurrence of substring in string

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

    General solution: replace any specified instance(s) of a substring [pattern] with another string.

    def replace(instring,pattern,replacement,n=[1]):
      """Replace specified instance(s) of pattern in string.
    
      Positional arguments
        instring - input string
         pattern - regular expression pattern to search for
     replacement - replacement
    
      Keyword arguments
               n - list of instances requested to be replaced [default [1]]
    
    """
      import re
      outstring=''
      i=0
      for j,m in enumerate(re.finditer(pattern,instring)):
        if j+1 in n: outstring+=instring[i:m.start()]+replacement
        else: outstring+=instring[i:m.end()]
        i=m.end()
      outstring+=instring[i:]
      return outstring
    

提交回复
热议问题