partial / wildcard string match in 'in' and 'list.index()'
Patrick Hall
pathall at gmail.com
Fri May 28 02:31:36 EDT 2004
Hi,
> 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")
I'm not sure if this is what you had in mind, but you can use list
comprehensions:
fruits=["apples","oranges","mangoes","bananas"]
import re
1. [fruit for fruit in fruits if re.match("man.*",fruit)]
2. [fruits.index(fruit) for fruit in fruits if re.match("man.*",fruit)]
3. [fruit for fruit in fruits if re.match(r".*an.*",fruit)]
4. [fruits.index(fruit) for fruit in fruits if re.match("man*",fruit)]
Note also that I think you're looking for
.*
instead of just
*
in your regular expressions.
> or is there any way to achieve an equivalent effect
> short of doing a while loop?
I personally am not so sure a while loop wouldn't be clearer in this
case -- things like "fruit for fruit in fruits" are pretty unreadable
to me.
Cheers,
Pat
More information about the Python-list
mailing list