Finding the items in a list by comparing with two string inputs

Question:

I have two string data like below

text1 = "hello how are you"
text2 = "hello how is professional life"

Then also I have a list of items which can/cannot be present in two strings like

test_data = ["are","how", "you","test","test2"]

Using this I will get items in test_data which are not present in text1.

[word for word in test_data if word not in text1]

Here the output obtained is

['are', 'you', 'test', 'test2']

In this case, test and test2 are not present in the first and second string too. So I don’t expect that in the result. So the expected result is

['are', 'you'] 

I am trying to find the data which is present only in text1 and not in text2.

Asked By: imhans4305

||

Answers:

Just extend your approach by a second condition:

[word for word in test_data if word  in text1 and word not in text2]
Answered By: Jacob
text1 = "hello how are you"
text2 = "hello how is professional life"

a = text1.split()
b = text2.split()

# print an array that has the words that are not in the other array
print(list(set(a) - set(b)))

output:

['are', 'you']
Answered By: DeltaHaxor
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.