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.

 
1
word: str
2
word = "banana"
3
if word == "banana":
4
    print("Yes, we have bananas!")
5
else:
6
    print("Yes, we have NO bananas!")
7

(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.

10
 
1
word: str
2
word = "zebra"
3
4
if word < "banana":
5
    print("Your word, " + word + ", comes before banana.")
6
elif word > "banana":
7
    print("Your word, " + word + ", comes after banana.")
8
else:
9
    print("Yes, we have no bananas!")
10

(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?

5
 
1
print(str("apple" < "banana"))
2
3
print(str("apple" == "Apple"))
4
print(str("apple" < "Apple"))
5

(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"



You have attempted 1 of 7 activities on this page
Next Section - 9.6. Traversal and the for Loop: By Index