Python wildcard search in string


Lets say that I have a list

list = ['this','is','just','a','test']

how can I have a user do a wildcard search?

Search Word: 'th_s'

Would return 'this'

This question is tagged with python

~ Asked on 2012-07-11 06:54:58

The Best Answer is


Regular expressions are probably the easiest solution to this problem:

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = [string for string in l if re.match(regex, string)]

~ Answered on 2012-07-11 07:00:59


Use fnmatch:

import fnmatch
lst = ['this','is','just','a','test']
filtered = fnmatch.filter(lst, 'th?s')

If you want to allow _ as a wildcard, just replace all underscores with '?' (for one character) or * (for multiple characters).

If you want your users to use even more powerful filtering options, consider allowing them to use regular expressions.

~ Answered on 2012-07-11 06:57:55

Most Viewed Questions: