Let us see how to compare Strings in Python.
Method 1: Using Relational Operators
The relational operators compare the Unicode values of the characters of the strings from the zeroth index till the end of the string. It then returns a boolean value according to the operator used.
“Geek” == “Geek” will return True as the Unicode of all the characters are equal
In case of “Geek” and “geek” as the unicode of G is \u0047 and of g is \u0067
“Geek” < “geek” will return True and
“Geek” > “geek” will return False
True True False False
The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands refer to the same object or not. The same is the case for != and is not.
Let us understand this with an example:
ID of str1 = 0x7f6037051570 ID of str2 = 0x7f6037051570 ID of str3 = 0x7f6037051570 True True True ID of changed str1 = 0x7f60356137d8 ID of str4 = 0x7f60356137a0 False
The object ID of the strings may vary on different machines. The object IDs of str1, str2 and str3 were the same therefore they the result is True in all the cases. After the object id of str1 is changed, the result of str1 and str2 will be false. Even after creating str4 with the same contents as in the new str1, the answer will be false as their object IDs are different.
Vice-versa will happen with is not.
Method 3: Creating a user-defined function.
By using relational operators we can only compare the strings by their unicodes. In order to compare two strings according to some other parameters, we can make user-defined functions.
In the following code, our user-defined function will compare the strings based upon the number of digits.
False False True
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course