Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Check if two words are in a string

Tags:

python

I would like to check whether 2 words "car" and "motorbike" are in each element of an array in Python. I know how to check for one word with in but have no idea how to do with 2 words. Really appreciate any help

like image 532
TDo Avatar asked Sep 24 '26 19:09

TDo


1 Answers

Two word solution:

for string in array:
    if 'car' in string and 'motorbike' in string.split():
        print("Car and motorbike are in string")

n-word solution to check if all words in test_words are in string:

test_words = ['car', 'motorbike']
contains_all = True

for string in array:
    for test_word in test_words:
        if test_word not in string.split()::
            contains_all = False
            break
    if not contains_all:
        break

if contains_all:
    print("All words in each string")
else:
    print("Not all words in each string")
like image 64
Michel Touw Avatar answered Sep 27 '26 08:09

Michel Touw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!