Sub topic 11
Checking what kind of characters a string holds
This chapter assumes you can call string methods, loop over a string, and read if statements. Earlier chapters covered methods that find and change text. The methods here answer a different question: what kind of characters does this string contain? Each one returns True or False and never changes the string.
The four basic checks
| Method | True when every character is... |
|---|---|
| `isalpha()` | a letter |
| `isdigit()` | a digit character |
| `isalnum()` | a letter or a digit |
| `isspace()` | whitespace (space, tab, newline, and similar) |
The word "every" matters. These methods test the whole string, not a part of it. A string must also be non-empty to pass.
samples = ["abc", "123", "abc123", " \t", "", "a b", "-5", "3.5"]
for s in samples:
print(repr(s), s.isalpha(), s.isdigit(), s.isalnum(), s.isspace())Here is what each sample returns, in the order alpha, digit, alnum, space:
| String | alpha | digit | alnum | space |
|---|---|---|---|---|
| `"abc"` | True | False | True | False |
| `"123"` | False | True | True | False |
| `"abc123"` | False | False | True | False |
| `" \t"` | False | False | False | True |
| `""` | False | False | False | False |
| `"a b"` | False | False | False | False |
| `"-5"` | False | False | False | False |
| `"3.5"` | False | False | False | False |
The last three rows catch many beginners. A space, a minus sign, and a decimal point are not letters or digits, so "a b", "-5", and "3.5" fail every check.
Testing one character at a time
To count or filter characters, call the method on each character of the string.
text = "R2-D2 beeps!"
letters = sum(ch.isalpha() for ch in text)
digits = sum(ch.isdigit() for ch in text)
print(letters, digits) # 7 2
only_letters = "".join(ch for ch in text if ch.isalpha())
print(only_letters) # RDbeepssum works here because True counts as 1 and False counts as 0.
Unicode: letters and digits are broader than ASCII
These methods follow Unicode, not just the characters a-z and 0-9. "é".isalpha() is True. Digits are trickier, because Python has three related methods.
print("²".isdigit(), "²".isdecimal(), "²".isnumeric()) # True False True
print("½".isdigit(), "½".isnumeric()) # False True
try:
int("²")
except ValueError:
print("int rejects it")isdecimal() is the strictest, and it is the one that matches what int() accepts. isdigit() also accepts characters such as superscripts, and isnumeric() also accepts fractions. So "²".isdigit() is True while int("²") fails.
Validation versus conversion
A check such as isdigit() says nothing about signs, decimal points, or surrounding spaces. For numbers, the usual approach is to attempt the conversion.
def to_int(text):
try:
return int(text.strip())
except ValueError:
return None
print(to_int(" 42 ")) # 42
print(to_int("-5")) # -5
print(to_int("4x")) # NoneUse the character checks for classifying text, such as "is this a username made of letters and digits?". Use int() or float() with try for numbers. Some patterns, such as "letters, then a dash, then four digits", are beyond these methods. That is where the re module comes in, as a later chapter explains.
Exercise
What do "".isdigit() and "12.5".isdigit() each return, and why? Which approach would you use to check that "12.5" is a valid number?
Show answer
Both return False. The empty string fails because these methods need at least one character, and "12.5" fails because "." is not a digit. To validate it as a number, call float("12.5") inside try/except ValueError instead of using a character check.