Python String Comparison

Filed Under: Python

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.


fruit1 = 'Apple'

print(fruit1 == 'Apple')
print(fruit1 != 'Apple')
print(fruit1 < 'Apple')
print(fruit1 > 'Apple')
print(fruit1 <= 'Apple')
print(fruit1 >= 'Apple')

Output:


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.")

Output:


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'))

Output:


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')

Output: 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')

Output:


False
False

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages