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

J

Jon Perez

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?
 
P

Peter Otten

Jon said:
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?
.... pattern = pattern.lower()
.... for i, n in enumerate(seq):
.... if fnmatch.fnmatch(n.lower(), pattern):
.... return i
.... return -1
........ result = find(seq, pattern)
.... if result == -1:
.... raise ValueError
.... return result
........ return find(seq, pattern) != -1
....
If you want case-sensitive matches, use fnmatchcase() and remove the
..lower() conversions.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top