Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare strings if something is the same 2 times

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading