To compare two strings, we mean that we want to identify whether the two strings are equivalent to each other or not, or perhaps which string should be greater or smaller than the other.
This is done using the following operators:
==: This checks whether two strings are equal
!=: This checks if two strings are not equal
<: This checks if the string on its left is smaller than that on its right
<=: This checks if the string on its left is smaller than or equal to that on its right
>: This checks if the string on its left is greater than that on its right
>=: This checks if the string on its left is greater than or equal to that on its right
String comparison in Python takes place character by character. That is, characters in the same positions are compared from both the strings.
If the characters fulfill the given comparison condition, it moves to the characters in the next position. Otherwise, it merely returns
Note: Some points to remember when using string comparison operators:
- The comparisons are case-sensitive, hence same letters in different letter cases(upper/lower) will be treated as separate characters
- If two characters are different, then their Unicode value is compared; the character with the smaller Unicode value is considered to be lower.
The code widget below uses the comparison operators that we have talked about above to compare different strings. Before we take a look at the code, below are the Unicode values for all the characters used in the code snippet:
name = 'John' name2 = 'john' name3 = 'doe' name4 = 'Doe' print("Are name and name 1 equal?") print (name == name2) print("Are name and name3 different?") print (name != name3) print("Is name less than or equal to name2?") print (name <= name2) print("Is name3 greater than or equal to name 2?") print (name3 >= name2) print("Is name4 less than name?") print (name4 < name)
View all Courses