Fastest Python method for search and replace on a large string

前端 未结 3 1188
半阙折子戏
半阙折子戏 2020-12-30 03:49

I\'m looking for the fastest way to replace a large number of sub-strings inside a very large string. Here are two examples I\'ve used.

findall() feels simpler and

3条回答
  •  抹茶落季
    2020-12-30 04:31

    By the way, your code with findall_replace() isn't safe, it can return unawaited results:

    ch = 'sea sun ABC-ABC-DEF bling ranch micABC-DEF fish'
    
    import re
    
    def findall_replace(text, reg, rep):
        for gr in reg.findall(text):
            text = text.replace(gr, rep)
            print 'group==',gr
            print 'text==',text
        return '\nresult is : '+text
    
    pat = re.compile('ABC-DE')
    rep = 'DEFINITION'
    
    print 'ch==',ch
    print
    print findall_replace(ch, pat, rep)
    

    display

    ch== sea sun ABC-ABC-DEF bling ranch micABC-DEF fish
    
    group== ABC-DE
    text== sea sun ABC-DEFINITIONF bling ranch micDEFINITIONF fish
    group== ABC-DE
    text== sea sun DEFINITIONFINITIONF bling ranch micDEFINITIONF fish
    
    result is : sea sun DEFINITIONFINITIONF bling ranch micDEFINITIONF fish
    

提交回复
热议问题