9.5. String Comparison¶
The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.
word: str
word = "banana"
if word == "banana":
print("Yes, we have bananas!")
else:
print("Yes, we have NO bananas!")
(ch08_comp1)
Other comparison operations are useful for putting words in lexicographical order. This is similar to the alphabetical order you would use with a dictionary, except that all the uppercase letters come before all the lowercase letters.
word: str
word = "zebra"
if word < "banana":
print("Your word, " + word + ", comes before banana.")
elif word > "banana":
print("Your word, " + word + ", comes after banana.")
else:
print("Yes, we have no bananas!")
(ch08_comp2)
It is probably clear to you that the word apple would be less than
(come before) the word banana
. After all, a is before b in
the alphabet. But what if we consider the words apple
and
Apple
? Are they the same?
print(str("apple" < "banana"))
print(str("apple" == "Apple"))
print(str("apple" < "Apple"))
(chp08_ord1)
Check your understanding
strings-8-1: Evaluate the following comparison:
"Dog" < "Doghouse"
strings-8-2: Evaluate the following comparison:
"dog" < "Dog"
strings-8-3: Evaluate the following comparison:
"dog" < "Doghouse"