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'
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.
If you want to allow _ as a wildcard, just replace all underscores with '?' (for one character) or * (for multiple characters).
In Python, we can implement wildcards using the regex (regular expressions) library.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With