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
.
Answers:
Just extend your approach by a second condition:
[word for word in test_data if word in text1 and word not in text2]
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']
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
.
Just extend your approach by a second condition:
[word for word in test_data if word in text1 and word not in text2]
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']