9.9. Characters

As you recall from our discussion of variable names, that uppercase and lowercase letters are considered to be different from one another. The way the computer knows they are different is that each character is assigned a unique integer value. “A” is 65, “B” is 66, and “5” is 53. The way you can find out the so-called ordinal value for a given character is to use a character function called ord.

When you compare characters or strings to one another, Python converts the characters into their equivalent ordinal values and compares the integers from left to right. As you can see from the example above, “a” is greater than “A” so “apple” is greater than “Apple”.

Humans commonly ignore capitalization when comparing two words. However, computers do not. A common way to address this issue is to convert strings to a standard format, such as all lowercase, before performing the comparison.

There is also a similar function called chr that converts integers into their character equivalent.

One thing to note in the last two examples is the fact that the space character has an ordinal value (32). Even though you don’t see it, it is an actual character. We sometimes call it a nonprinting character.

It is worth noting that there is some organization to the the ordinal values. All of the alphabetic lettes are in order. Observe:

This has several implications. It is possible to tell if a character is a uppercase or lowercase letter just by examining the character’s ordinal value. It is also possible to convert a character between uppercase and lowercase by changing its ordinal value.

Check your understanding

    strings-8-2-1: What will the following program print when run?

    ordinal: int
    character: str
    ordinal = ord('A')
    character = chr(ordinal + 1)
    print(character)
    
  • a
  • The orinal value of a is not one above A.
  • b
  • The ordinal value of b is not noe above A.
  • A
  • The ordinal value of A is modified by adding 1 before converting it back to a string.
  • B
  • Yes, the character one above A is B.

    strings-8-2-2: What will the following program print when run?

    ordinal: int
    difference: int
    character: str
    ordinal = ord('B')
    difference = ord('a') - ord('A')
    character = chr(ordinal + difference)
    print(character)
    
  • a
  • The orindal value of a is used to compute the difference, not the character.
  • b
  • Yes, the difference between a and A is the same difference between b and B.
  • A
  • The orindal value of A is used to compute the difference, not the character.
  • B
  • The ordinal value of B is modified by adding the difference between a and A before converting it back to a string.
You have attempted of activities on this page
Next Section - 9.10. Summary