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

Jon Perez jbperez808 at yahoo.com
Fri May 28 03:41:56 EDT 2004


Patrick Hall wrote:

 > 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)]

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.



More information about the Python-list mailing list