Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Python's string.replace vs re.sub

Tags:

python

regex

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.

like image 788
wag2639 Avatar asked Apr 14 '11 19:04

wag2639


People also ask

Is Re sub faster than STR replace?

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.

Is regex faster than string replace Python?

Two-regex is now 15.9 times slower than string replacement, and regex/lambda 38.8 times slower.

How do I replace only part of a match with Python re sub?

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.

Does re sub replace all occurrences?

By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.


2 Answers

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.

like image 102
Sven Marnach Avatar answered Sep 21 '22 13:09

Sven Marnach


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 
like image 23
chmullig Avatar answered Sep 18 '22 13:09

chmullig