Home > Blockchain >  Compare strings if something is the same 2 times
Compare strings if something is the same 2 times

Time:11-08

Something like:

string_one = "hello world one"
string_two = "hello john one"
if string_one = string_two:
    do something

So if it detects 2 words in 2 (or more) strings that are the same do something. But I can't figure out how to do it.

CodePudding user response:

Use split() to turn the strings into lists of words, then turn them into sets so you can take the intersection and see if its len is greater than 2.

>>> string_one = "hello world one"
>>> string_two = "hello john one"
>>> set(string_one.split()) & set(string_two.split())
{'hello', 'one'}
>>> if len(set(string_one.split()) & set(string_two.split())) >= 2:
...     print("at least two words are the same!")
...
at least two words are the same!

CodePudding user response:

Using list comparison

string_one = "hello world one"
string_two = "hello john one"

matched = [i for i in string_one.split() if i in string_two.split()]
print(matched)

output List

['hello', 'one']
>>> 

You can set condition by

print(len(matched))

output length

2

Uisng condition accordingly

if(len(matched)) >=2:
    print("2 or more sub words matched")
  • Related