Today we’ll be talking about string comparison and membership.
Here’s the video version of this article if you prefer to watch it first:
String Comparison
We can use all the comparison operators to compare strings. Each character in Unicode is represented by a number and these numbers are compared. This is how string comparing works. It means, the order is not strictly alphabetical, because all capital letters come before small letters in Unicode.
We have the following comparison operators:
These two should be equal:
>>> "hello" == "hello"
True
These should be not equal:
>>> a = "hello"
>>> b = "hi"
>>> a != b
True
The first character to differ is the second one, ‘i’ comes after ‘e’:
>>> "hi" > "hello"
True
Capital ‘Y’ comes before small ‘y’:
>>> "Yes" < "yes"
True
We can confirm this by means of the ord function, which gives us the Unicode number of the character:
>>> ord("Y"), ord("y")
(89, 121)
These two are equal, so the first one must also be greater or equal to the other:
>>> "hello" >= "hello"
True
‘F’ is a capital letter, so it comes earlier than any small letter. As ‘F’ is less than ‘a’, it’s automatically also less than or equal to ‘a’:
>>> "F" <= "a"
True
Membership
We can check if a particular element is contained or not in the string. We use the membership operators in and not in:
>>> text = "I need help."
>>> "n" in text
True
>>> "i" in text # Capital I is contained but not the small one.
False
>>> "Z" not in text
True