How do I compare two strings in python?
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
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
>>> 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']