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

Peter Otten __peter__ at web.de
Fri May 28 02:47:25 EDT 2004


Jon Perez wrote:

> For a given list:
> 
> fruits=["apples","oranges","mangoes","bananas"]
> 
> 
> 
> 
> Is it possible to do wildcard matches like shown below?
> 
> 1. "man*" in fruits
> 
> 2. fruits.index("man*")
> 
> 3. "*nanas*" in fruits
> 
> 4. fruits.index("*nanas")
> 
> 
> 
> or is there any way to achieve an equivalent effect
> short of doing a while loop?

>>> import fnmatch
>>> def find(seq, pattern):
...     pattern = pattern.lower()
...     for i, n in enumerate(seq):
...             if fnmatch.fnmatch(n.lower(), pattern):
...                     return i
...     return -1
...
>>> def index(seq, pattern):
...     result = find(seq, pattern)
...     if result == -1:
...             raise ValueError
...     return result
...
>>> def contains(seq, pattern):
...     return find(seq, pattern) != -1
...
>>> fruit = "apples oranges mangoes bananas".split()
>>> contains(fruit, "man*")
True
>>> contains(fruit, "*nas")
True
>>> index(fruit, "*ANA*")
3
>>> find(fruit, "*")
0
>>> find(fruit, "m*s")
2
>>> find(fruit, "m*x")
-1
>>>

If you want case-sensitive matches, use fnmatchcase() and remove the
.lower() conversions.

Peter




More information about the Python-list mailing list