Relational Operators
You can compare two strings in Python with == (equal to) and != (not equal to). Each comparison gives a Boolean result: True or False.
A string comparison with == is exact and case sensitive. Capital and lower-case letters are different characters, and a space counts as a character too, so the comparison checks the text exactly as it is written.
| Comparison | Result |
|---|---|
"Platform 3" == "Platform 3" | True |
"Platform 3" == "platform 3" | False |
"Platform 3" != "Platform3" | True |
In the second row the lower-case p makes the two strings different. In the third row the missing space makes the strings different, so they are not equal and != gives True. This program compares what you type with a stored string using ==:
planet = input("Name the largest planet: ")
if planet == "Jupiter":
print("That is right")
else:
print("Not an exact match")Output when the user types jupiter:
Name the largest planet: jupiter
Not an exact match
A string is a different data type from an integer or a float. "7.50" == 7.50 is False: the characters look like a number, but one value is text and the other is a number. When you use input(), the result is always a string, so typed digits are still text. To compare that input with a number, convert it first with int() or float(); for example, float("7.50") == 7.50 is True, because both values are now the number 7.5.
You only need == and != for comparing strings. Comparing strings with <, >, <= or >= is not required.
OCR GCSE Computer Science · Relational Operators