Python String comparison can be performed using equality (==) and comparison (<, >, !=, <=, >=) operators. There are no special methods to compare two strings.
Python String Comparison
Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller.
Let’s look through some examples for string comparison.
Copyfruit1 = 'Apple' print(fruit1 == 'Apple') print(fruit1 != 'Apple') print(fruit1 < 'Apple') print(fruit1 > 'Apple') print(fruit1 <= 'Apple') print(fruit1 >= 'Apple')
CopyTrue False False False True True
Both the strings are exactly the same, hence they are equal. So equality operator is returning True in this case.
Let’s look at another example where we will get inputs from the user and then compare them.
Copyfruit1 = input('Please enter the name of first fruit:\n') fruit2 = input('Please enter the name of second fruit:\n') if fruit1 < fruit2: print(fruit1 + " comes before " + fruit2 + " in the dictionary.") elif fruit1 > fruit2: print(fruit1 + " comes after " + fruit2 + " in the dictionary.") else: print(fruit1 + " and " + fruit2 + " are same.")
CopyPlease enter the name of first fruit: Apple Please enter the name of second fruit: Banana Apple comes before Banana in the dictionary. Please enter the name of first fruit: Orange Please enter the name of second fruit: Orange Orange and Orange are same.
Let’s see if the comparison is case sensitive or not? Also if ‘a’ comes ‘A’?
Copyprint('apple' == 'Apple') print('apple' > 'Apple') print('A unicode is', ord('A'), ',a unicode is', ord('a'))
CopyFalse True A unicode is 65 ,a unicode is 97
So “Apple” is smaller when compared to “apple” because of their Unicode values. We are using ord() function to print the Unicode code point value of the characters.
What if one of the string is made of second string and some additional characters?
Copyprint('Apple' < 'ApplePie')
If the characters sequence are the same in both the strings but one of them have some additional characters, then the larger length string is considered greater than the other one.
What if we use < and > operators to compare two equal strings?
Copyprint('apple' < 'apple') print('apple' > 'apple')
Obviously, both the strings are neither smaller nor greater than the other one. Hence the output is false in both the cases.