To compare strings alphabetically in Python, you can use the < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) operators.
a = "this is a string"
b = "another string"
if a < b:
print("a is less than b")
else:
print("a is greater than or equal to b")
#Output:
a is greater than or equal to b
Note that uppercase letters come before lowercase letters.
a = "this"
b = "This"
if a < b:
print("a is less than b")
else:
print("a is greater than or equal to b")
#Output:
a is less than b
When working with strings, sometimes it can be useful to compare strings alphabetically. You can easily compare strings in Python.
The < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) operators work just like they work with numbers. String comparison, using these operators, compares the unicode representation of the characters.
Below are some examples of comparing strings alphabetically in Python.
print("this" < "word")
print("word" < "this")
print("another" <= "word")
print("another" <= "another")
#Output:
True
False
True
True
Comparing Strings Alphabetically in Python
As mentioned above, when comparing strings, Python is comparing the unicode representation of the characters from left to right.
When working with strings which have uppercase and lowercase characters, you have to be careful since uppercase characters come before lowercase characters in unicode.
You can see the unicode value of a character with the Python ord() function. Below shows you the difference between an uppercase and lowercase "a".
print(ord("a"))
print(ord("A"))
#Output:
97
65
If you are comparing strings with a mix of uppercase and lowercase letters, then it might make sense to use either the lower() or upper() functions to convert your string to have all uppercase or all lowercase characters.
uppercase = "HELLO"
lowercase = "hello"
print(uppercase < lowercase)
print(uppercase.lower() < lowercase.lower())
print(uppercase.lower() == lowercase.lower())
#Output:
True
False
True
Hopefully this article has been helpful for you to learn how to compare strings alphabetically using Python.