Michael Tenson
Michael Tenson

Reputation: 125

Filter list of strings starting with specific keyword

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

Answers (4)

Dadep
Dadep

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

Deniz Kaplan
Deniz Kaplan

Reputation: 1609

As everybody mentioned before, str.startswith is your function. You can study regex patterns for more complex operations. regex

Upvotes: 0

dizzyf
dizzyf

Reputation: 3693

for word in WordList:
    if word.startswith(PartialWord):
        print word    

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

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 return False. prefix can also be a tuple 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

Related Questions