Home > Mobile >  Find matching words from a list by passing string in python
Find matching words from a list by passing string in python

Time:07-30

I have a list with names, I am trying to search list by passing a string, as output I need all the names from the list that matches to the word.

EX:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'HiHello', 'Hellotent', 'Tenthello']
sub = "Hello"

matches = [match for match in ls if sub in match]

print(matches)

['Hello from AskPython', 'Hello', 'Hello boy!', 'HiHello', 'Hellotent', 'Tenthello']

But Expected output is :

['Hello from AskPython', 'Hello', 'Hello boy!']

In the above example "Hello" appeared in between name, I need to exclude such words.

CodePudding user response:

You can use regular expression or split the string and use any() to check if the sub is present:

matches = [s for s in ls if any(sub == word for word in s.split())]
print(matches)

Prints:

['Hello from AskPython', 'Hello', 'Hello boy!']

CodePudding user response:

Here is how you can achieve this : instead of checking if sub is in match you can split(by empty space) the match string and only check if the first element of the split is equal to sub or not.

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'HiHello', 'Hellotent', 
     'Tenthello']
sub = "Hello"

matches = [match for match in ls if match.split()[0] == sub]

print(matches)
  • Related