Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python wildcard search in string

Tags:

python

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'

like image 896
Austin Avatar asked Jul 11 '12 06:07

Austin


People also ask

How do you do a wildcard search in Python?

the Asterisk * Wildcard in PythonThe * character or the asterisk can specify any number of characters. The asterisk * is mostly utilized at the end of the given root word and when there is a need to search for endings with several possibilities for the given root word.

How do you add a wildcard to a string in Python?

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

Are there wildcards in Python?

In Python, we can implement wildcards using the regex (regular expressions) library.

How do you use a wildcard when searching?

Wildcards take the place of one or more characters in a search term. A question mark (?) is used for single character searching. An asterisk (*) is used for multiple character searching.


1 Answers

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.

like image 125
phihag Avatar answered Oct 13 '22 16:10

phihag