While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python String comparison can be performed using equality (==) and comparison (<, >, !=, <=, >=) operators. There are no special methods to compare two strings.
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.
fruit1 = 'Apple' print(fruit1 == 'Apple') print(fruit1 != 'Apple') print(fruit1 < 'Apple') print(fruit1 > 'Apple') print(fruit1 <= 'Apple') print(fruit1 >= 'Apple')
True 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.
fruit1 = 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.")
Please 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’?
print('apple' == 'Apple') print('apple' > 'Apple') print('A unicode is', ord('A'), ',a unicode is', ord('a'))
False 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?
print('Apple' < 'ApplePie')
True 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?
print('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.
You can checkout complete python script and more Python examples from our GitHub Repository.
If you’ve enjoyed this tutorial and our broader community, consider checking out our DigitalOcean products which can also help you achieve your development goals.