Replace nth occurrence of substring in string

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

    I've tweaked @aleskva's answer to better work with regex and wildcards:

    import re
    
    def replacenth(string, sub, wanted, n):
        pattern = re.compile(sub)
        where = [m for m in pattern.finditer(string)][n-1]
        before = string[:where.start()]
        after = string[where.end():]
        newString = before + wanted + after
    
        return newString
    
    replacenth('abdsahd124njhdasjk124ndjaksnd124ndjkas', '1.*?n', '15', 1)
    

    This gives abdsahd15jhdasjk124ndjaksnd124ndjkas. Note the use of ? to make the query non-greedy.

    I realise that the question explicitly states that they didn't want to use regex, however it may be useful to be able to use wildcards in a clear fashion (hence my answer).

提交回复
热议问题