Fastest Python method for search and replace on a large string

前端 未结 3 1179
半阙折子戏
半阙折子戏 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:38

    The standard method is to use the built-in

    re.sub(reg, rep, text)
    

    Incidentally the reason for the performance difference between your versions is that each replacement in your first version causes the entire string to be recopied. Copies are fast, but when you're copying 10 MB at a go, enough copies will become slow.

提交回复
热议问题