Skip to main content

Section 7.21 Character Classification

It is often helpful to examine a character and test whether it is upper- or lowercase, or whether it is an alphabetic character or a digit. Because we can do string comparisons, we could write a function like this to test for lower case letters:
def is_lower_case(char):
    if char >= 'a' and char <= 'z':
        return True
    else:
        return False
That works great—as long as you are only dealing with English. But what about characters like ç, Ñ, Δ, or even 年? Luckily, Python provides us with several string methods that help us classify characters.
Table 7.21.1. Character Classification Methods
Method Returns True when str...
str.isalpha() consists of all alphabetic characters
str.isdigit() consists of all digits
str.islower() consists of all lower case characters
str.isupper() consists of all upper case characters
str.isspace() consists of all whitespace
For all these methods, the string must consist of one or more characters in order to return True; the empty string returns False for all of these. The following program shows how the classification works. The web version of Python that activecode uses does not handle non-English characters properly, so you will have to copy and paste the following code into your favorite development environment and run it from there.
def classify(str):
  if str.isalpha():
      print(f"{str} is alpha")
  if str.isdigit():
      print(f"{str} is digit")
  if str.islower():
      print(f"{str} is lower case")
  if str.isupper():
      print(f"{str} is upper case")
  print() # for spacing and readability
  
classify("m")
classify("M")
classify("Δ")
classify("年")
classify("1234321")
classify("Français")
For more information, consult the string documentation (see String Methods 1 ).

Note 7.21.2.

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
https://docs.python.org/3/library/stdtypes.html#string-methods