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.
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
Videos
I am working on a code I found on Github and I am not familiar with regex. Can someone please explain the meaning of this re.sub("^\s*(.-)\s*$", "%1", s).replace("\\n", "\n")
s is the variable containing the string of interest.
Simply use \1 instead of $1:
In [1]: import re
In [2]: method = 'images/:id/huge'
In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'
Also note the use of raw strings (r'...') for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.
A backreference to the whole match value is \g<0>, see re.sub documentation:
The backreference
\g<0>substitutes in the entire substring matched by the RE.
See the Python demo:
import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge
If you need to perform a case insensitive search, add flag=re.I:
re.sub(r':[a-z]+', r'<span>\g<0></span>', method, flags=re.I)