Matching Strings
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Fri Feb 9 22:07:43 EST 2007
On Fri, 09 Feb 2007 16:17:31 -0800, James Stroud wrote:
> Assuming item is "(u'ground water',)"
>
> import re
> item = re.compile(r"\(u'([^']*)',\)").search(item).group(1)
Using a regex is a lot of overhead for a very simple operation.
If item is the string "(u'ground water',)"
then item[3:-3] will give "ground water".
>>> import re, timeit
>>> item = "(u'ground water',)"
>>> timeit.Timer('item[3:-3]', 'from __main__ import item').repeat()
[0.56174778938293457, 0.53341794013977051, 0.53485989570617676]
>>> timeit.Timer( \
... '''re.compile(r"\(u'([^']*)',\)").search(item).group(1)''', \
... 'from __main__ import item; import re').repeat()
[9.2723720073699951, 9.2299859523773193, 9.2523660659790039]
However, as many others have pointed out, the Original Poster's problem
isn't that item has leading brackets around the substring he wants, but
that it is a tuple.
--
Steven.
More information about the Python-list
mailing list