Rahul Anand
Rahul Anand

Reputation: 573

Python Check if a string is there in a sentence from a list of strings

I have a list of words like substring = ["one","multiple words"] from which i want to check if a sentence contains any of these words.

sentence1 = 'This Sentence has ONE word'
sentence2 = ' This sentence has Multiple Words'

My code to check using any operator:

any(sentence1.lower() in s for s in substring)

This is giving me false even if the word is present in my sentence. I don't want to use regex as it would be an expensive operation for huge data.

Is there any other approach to this?

Upvotes: 0

Views: 5012

Answers (3)

Flux
Flux

Reputation: 10950

As mentioned in other answers, this is what will get you the correct answer if you want to detect substrings:

any(s in sentence1.lower() for s in substring)

However, if your goal is to find words instead of substrings, this is incorrect. Consider:

sentence = "This is an aircraft"
words = ["air", "hi"]
any(w in sentence.lower() for w in words)  # True.

The words "air" and "hi" are not in the sentence, but it returns True anyway. Instead, if you want to check for words, you should use:

any(w in sentence.lower().split(' ') for w in words)

Upvotes: 2

Muneeb
Muneeb

Reputation: 99

use this scenario.

a="Hello Moto"
    a.find("Hello")

It will give you an index in return. If the string is not there it will return -1

Upvotes: 0

wookiekim
wookiekim

Reputation: 1176

I think you should reverse your order:

any(s in sentence1.lower() for s in substring)

you're checking if your substring is a part of your sentence, NOT if your sentence is a part of any of your substrings.

Upvotes: 7

Related Questions