partial / wildcard string match in 'in' and 'list.index()'

Josiah Carlson jcarlson at uci.edu
Fri Jun 4 03:25:07 EDT 2004


> These would work, but I was wondering if there was some compact
> way to get 'in' and lists.index() to do wildcard matching as opposed
> to exact matching.

Short answer: no.

Long answer:
There is a regular expression library, aptly called 're', for non-exact 
string searching.

The standard string methods only do exact searching likely because there 
are algorithms that make it fast (linear in the length of the searched 
string), that are also quite small.

There exist very simple looking regular expressions that force searches 
to take exponential (in the length of the pattern) time to search, and 
are generally fairly large.

An example of an exponentially slow regular expression is contained in 
the following example...
 >>> import re
 >>> import time
 >>> def test(n):
...     a = 100*'0'
...     t = time.time()
...     re.search('(0+)'*n, a)
...     return time.time()-t
...
 >>> for i in xrange(18, 23):
...     print i, test(i)
...
18 0.141000032425
19 0.266000032425
20 0.530999898911
21 1.07899999619
22 2.1400001049
 >>>

Trust me, you don't want that kind of slow down when you are searching 
in strings with "if i in 'somestring':".


  - Josiah



More information about the Python-list mailing list