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.
As long as you can make do with str. replace() , you should use it. It avoids all the pitfalls of regular expressions (like escaping), and is generally faster.
Two-regex is now 15.9 times slower than string replacement, and regex/lambda 38.8 times slower.
Put a capture group around the part that you want to preserve, and then include a reference to that capture group within your replacement text. @Amber: I infer from your answer that unlike str. replace(), we can't use variables a) in raw strings; or b) as an argument to re. sub; or c) both.
By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.
As long as you can make do with str.replace()
, you should use it. It avoids all the pitfalls of regular expressions (like escaping), and is generally faster.
str.replace()
should be used whenever it's possible to. It's more explicit, simpler, and faster.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With