You can compare strings in Python using the equality (
==) and comparison (
>=) operators. There are no special methods to compare two strings. In this article, you’ll learn how each of the operators work when comparing strings.
Python string comparison compares the characters in both strings one by one. When different characters are found, then their Unicode code point values are compared. The character with the lower Unicode value is considered to be smaller.
Declare the string variable:
fruit1 = 'Apple'
The following table shows the results of comparing identical strings (
Apple) using different operators.
|Not equal to||
|Less than or equal to||
|Greater than or equal to||
Both the strings are exactly the same. In other words, they’re equal. The equality operator and the other equal to operators return
If you compare strings of different values, then you get the exact opposite output.
If you compare strings that contain the same substring, such as
ApplePie, then the longer string is considered larger.
This example code takes and compares input from the user. Then the program uses the results of the comparison to print additional information about the alphabetical order of the input strings. In this case, the program assumes that the smaller string comes before the larger string.
fruit1 = input('Enter the name of the first fruit:\n') fruit2 = input('Enter the name of the 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 the same.")
Here’s an example of the potential output when you enter different values:
OutputEnter the name of first fruit: Apple Enter the name of second fruit: Banana Apple comes before Banana in the dictionary.
Here’s an example of the potential output when you enter identical strings:
OutputEnter the name of first fruit: Orange Enter the name of second fruit: Orange Orange and Orange are the same.
Note: For this example to work, the user needs to enter either only upper case or only lower case for the first letter of both input strings. For example, if the user enters the strings
Banana, then the output will be
apple comes after Banana in the dictionary, which is incorrect.
This discrepancy occurs because the Unicode code point values of uppercase letters are always smaller than the Unicode code point values of lowercase letters: the value of
a is 97 and the value of
B is 66. You can test this yourself by using the
ord() function to print the Unicode code point value of the characters.
In this article you learned how to compare strings in Python using the equality (
==) and comparison (
>=) operators. Continue your learning about Python strings.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.