Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two strings in python?

I have two strings like

string1="abc def ghi" 

and

string2="def ghi abc" 

How to get that this two string are same without breaking the words?

like image 412
user3064366 Avatar asked Feb 20 '14 09:02

user3064366


People also ask

Can you use == to compare strings in Python?

Python comparison operators can be used to compare strings in Python. These operators are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).

Can you use == to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do you compare 2 strings?

The compare() function compares two strings and returns the following values according to the matching cases: Returns 0, if both the strings are the same. Returns <0, if the value of the character of the first string is smaller as compared to the second string input.


1 Answers

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 
like image 127
oxfn Avatar answered Sep 28 '22 15:09

oxfn