How do I compare two strings in python if order does not matter?
Solution 1:
Seems question is not about strings equality, but of sets equality. You can compare them this way only by splitting strings and converting them to sets:
s1 = 'abc def ghi'
s2 = 'def ghi abc'
set1 = set(s1.split(' '))
set2 = set(s2.split(' '))
print set1 == set2
Result will be
True
Solution 2:
If you want to know if both the strings are equal, you can simply do
print string1 == string2
But if you want to know if they both have the same set of characters and they occur same number of times, you can use collections.Counter
, like this
>>> string1, string2 = "abc def ghi", "def ghi abc"
>>> from collections import Counter
>>> Counter(string1) == Counter(string2)
True
Solution 3:
>>> s1="abc def ghi"
>>> s2="def ghi abc"
>>> s1 == s2 # For string comparison
False
>>> sorted(list(s1)) == sorted(list(s2)) # For comparing if they have same characters.
True
>>> sorted(list(s1))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> sorted(list(s2))
[' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
Solution 4:
For that, you can use default difflib in python
from difflib import SequenceMatcher
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
then call similar() as
similar(string1, string2)
it will return compare as ,ratio >= threshold to get match result