str.replace
远快于正则替换,它更加显式,简单,快。
Ipython 环境测试:
In [1]: import re
In [2]: text = """For python 2.5, 2.6, should I be using string.replace or re.sub for basic text replacements.
In PHP, this was explicitly stated but I can't find a similar note for python.
"""
In [3]: timeit text.replace('e', 'X')
1000000 loops, best of 3: 735 ns per loop
In [4]: timeit re.sub('e', 'X', text)
100000 loops, best of 3: 5.52 us per loop
这段代码来自stackoverflow, timeit是ipython独有的magic功能.
我测了下,str.repalce 比 re.sub快2倍多一些(python2.7.13)。