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.

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.

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?

Check your understanding

    strings-8-1: Evaluate the following comparison:

    "Dog" < "Doghouse"
    
  • True
  • Both match up to the g but Dog is shorter than Doghouse so it comes first in the dictionary.
  • False
  • Strings are compared character by character.

    strings-8-2: Evaluate the following comparison:

    "dog" < "Dog"
    
  • True
  • d is greater than D according to the ord function (68 versus 100).
  • False
  • Yes, upper case is less than lower case according to the ordinal values of the characters.
  • They are the same word
  • Python is case sensitive meaning that upper case and lower case characters are different.

    strings-8-3: Evaluate the following comparison:

    "dog" < "Doghouse"
    
  • True
  • d is greater than D.
  • False
  • The length does not matter. Lower case d is greater than upper case D.
You have attempted of activities on this page
Next Section - 9.6. Traversal and the for Loop: By Index