What is built-in method sub

Arnaud Delobelle arnodel at googlemail.com
Mon Jan 11 22:15:15 CET 2010

Philip Semanchuk <philip at semanchuk.com> writes:
> I second the suggestion to use rstrip(), but for future reference you
> should also check out the compile() function in the re module. You
> might want to time the code above against a version using a compiled
> regex to see how much difference it makes.

The re module caches regex strings:

>>> import re
>>> foo = 'foo+'
>>> key = str, foo, 0
>>> re._cache.get(key)
>>> re.findall(foo, 'foo bar foooo')
['foo', 'foooo']
>>> re._cache.get(key)
<_sre.SRE_Pattern object at 0x3fcb60>

So it doesn't recompile a regex string which has already been compiled.


More information about the Python-list mailing list