Reputation: 125
How can I find a string (PartialWord
) inside a List (WordList
) in Python 2.7?
PartialWord = "ab"
WordList = ['absail', 'rehab', 'dolphin']
A search with a wildcard like: ab*
Where it would ONLY find the word, if it starts with those letters (i.e. the result should only give absail, but not rehab, despite both having 'ab').
The WordList would be a dictionary, which is over 700KB.
Upvotes: 9
Views: 18647
Reputation: 2788
you can do :
>>> WL = ['absail', 'rehab', 'dolphin']
>>> PW="ab"
>>> L=[a for a in WL if a[:len(PW)]==PW]
>>> L
['absail']
Upvotes: 0
Reputation: 1609
As everybody mentioned before, str.startswith
is your function. You can study regex patterns for more complex operations. regex
Upvotes: 0
Reputation: 48090
You may use str.startswith(..)
along with a list comprehension to get the list of the words starting with some string as:
>>> PartialWord = "ab"
>>> WordList = ['absail', 'rehab', 'dolphin']
>>> [word for word in WordList if word.startswith(PartialWord)]
['absail']
As per the str.startswith
document:
str.startswith(prefix[, start[, end]]):
Return
True
if string starts with the prefix, otherwise returnFalse
. prefix can also be atuple
of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
Upvotes: 18