Jarratt Perkins
Jarratt Perkins

Reputation: 303

Check if text within a list is withing a string

I would like to check against a list of words if they are within a string.

For Example:

listofwords = ['hi','bye','yes','no']

String = 'Hi how are you'
string2 = 'I have none of the words'

String 1 is true as it contains 'hi' and string2 is false as it does not.

I have tried the following code but it always returns false.

if any(ext in String for ext in listofwords):
   print(String)

I would also like to show what the matching word was to check this is correct.

Upvotes: 2

Views: 117

Answers (3)

Poojan
Poojan

Reputation: 3519

hi and Hi are different words. Use .lower before comparing.

if any(ext.lower() in String.lower() for ext in listofwords):
   print(String)

Update:

  • to print matching word use for loop to iterate and print words that match.

Example:

listofwords = ['hi','bye','yes','no']

String = 'Hi how are you'
string2 = 'I have none of the words'

for word in listofwords:
    if word.lower() in map(str.lower,String.split()): # map both of the words to lowercase before matching
        print(word)


for word in listofwords:
    if word.lower() in map(str.lower,string2.split()): # map both of the words to lowercase before matching
        print(word)

PS: Not the optimized version. You can store String.split results in a list and then start iterating that will save time for larger strings. But purpose of the code is to demonstrate use of lower case.

Upvotes: 5

Djaouad
Djaouad

Reputation: 22794

The problem is both with case-sensitivity and with using in directly with a string.

If you want to make your search case-insensitive, consider converting both the String and the word to lower case, also, you should split the string after lower casing it, if you want to properly search for words:

if any(ext.lower() in String.lower().split() for ext in listofwords):
   print(String)

Splitting avoids returning True for strings like no in none and only works if no (or any other word) is present on its own. So now the above will work for both String (it will print it) and for string2 (it will not print it).

Upvotes: 0

Carsten
Carsten

Reputation: 3048

Python is case sensitive. Hence hi is not equal to Hi. This works:

listofwords = ['hi','bye','yes','no']

String = 'hi how are you'
string2 = 'I have none of the words'

if any(ext in String for ext in listofwords):
   print(String)

Upvotes: 2

Related Questions