Sub topic 11
Checking what kind of characters a string holds
This chapter covers the is... methods on str. They answer yes/no questions about the characters in a string, such as "is this all digits?" or "is this only whitespace?". You should already know how to call string methods and write if statements, for loops and generator expressions. Earlier chapters showed that string methods return new values and never change the original string. These methods go one step further and return a plain bool.
What the checks have in common
Every method in this family looks at all the characters in the string and returns True only if every character passes. There are two rules that cause most bugs:
- An empty string returns
Falsefor most of them (isalpha,isdigit,isspaceand others). - The checks follow Unicode, not just ASCII.
"é".isalpha()isTrue, and so is"٣".isdigit()(an Arabic-Indic digit three).
for check in (str.isalpha, str.isdigit, str.isalnum, str.isspace):
print(check.__name__, check(""))Output:
isalpha False
isdigit False
isalnum False
isspace FalseA few methods behave differently for the empty string. "".isascii() and "".isprintable() both return True, because no character fails the test.
Letters, digits and whitespace
The most common checks are isalpha, isalnum and isspace.
print("naïve".isalpha()) # True
print("don't".isalpha()) # False, the apostrophe is not a letter
print("abc123".isalnum()) # True
print("abc 123".isalnum()) # False, the space fails
print("abc_1".isalnum()) # False, underscore is not alphanumeric
print(" \t\n".isspace()) # True
print("".isspace()) # Falseisalpha accepts letters from any script, so "日本".isalpha() is also True. isspace counts Unicode whitespace as well, including the non-breaking space "\u00a0". That is useful, because strip() removes the same characters.
cell = "\u00a0"
print(cell.isspace()) # True
print(repr(cell.strip())) # ''A check for "blank input" is therefore short and reliable:
def is_blank(text):
return text == "" or text.isspace()
print(is_blank("")) # True
print(is_blank(" ")) # True
print(is_blank(" a ")) # FalseThree kinds of "number"
Python has three digit-related methods. They differ in how wide a net they cast.
| Method | Accepts | Example that passes | Example that fails |
|---|---|---|---|
| `isdecimal` | Characters that form base-10 numbers, in any script | `"123"`, `"٣"` | `"²"`, `"½"` |
| `isdigit` | Everything `isdecimal` accepts, plus digit-like characters such as superscripts | `"²"` | `"½"` |
| `isnumeric` | Everything `isdigit` accepts, plus fractions and numerals such as `"五"` | `"½"`, `"五"` | `"1.5"` |
None of them accept a minus sign, a decimal point or a thousands separator.
for s in ["123", "²", "½", "٣", "五", "-5", "3.14", ""]:
print(repr(s), s.isdecimal(), s.isdigit(), s.isnumeric())Output:
'123' True True True
'²' False True True
'½' False False True
'٣' True True True
'五' False False True
'-5' False False False
'3.14' False False False
'' False False FalseThe gotcha is that isdigit can return True for text that int rejects:
s = "²"
print(s.isdigit()) # True
try:
int(s)
except ValueError:
print("int failed") # int failedisdecimal is the method that matches what int can parse, ignoring a sign and surrounding whitespace. It still accepts non-ASCII digits, and int("٣") is 3. If you want to accept only the ASCII digits 0 to 9, add isascii.
def parse_quantity(text):
text = text.strip()
if text.isascii() and text.isdecimal():
return int(text)
raise ValueError(f"not a non-negative integer: {text!r}")
print(parse_quantity(" 42 ")) # 42
for bad in ["-5", "٣", "4.5", ""]:
try:
parse_quantity(bad)
except ValueError as err:
print(err)Output:
42
not a non-negative integer: '-5'
not a non-negative integer: '٣'
not a non-negative integer: '4.5'
not a non-negative integer: ''Case checks
isupper, islower and istitle look at the case of letters. Characters that have no case, such as digits and punctuation, are ignored. The string still needs at least one cased character.
print("ABC".isupper()) # True
print("ABC 123!".isupper()) # True, digits and punctuation are ignored
print("123".isupper()) # False, no cased character at all
print("Abc".isupper()) # False
print("abc".islower()) # True
print("Hello World".istitle()) # True
print("Hello world".istitle()) # FalseThese methods check the current state of the string. To change case, use the case methods from the earlier chapter. They also do not give you a "has any uppercase letter" test. For that, check each character:
password = "secret7"
print(any(ch.isupper() for ch in password)) # False
print(any(ch.isdigit() for ch in password)) # TrueASCII, printable and identifier checks
Three more methods answer narrower questions.
isascii()isTrueif every character has a code point below 128. It is fast, and the empty string passes.isprintable()isFalseif the string contains control characters such as"\n"or"\t". A plain space counts as printable.isidentifier()isTrueif the text could be a Python variable name. Keywords like"class"still pass, so combine it withkeyword.iskeywordif that matters.
import keyword
print("abc".isascii(), "é".isascii(), "".isascii()) # True False True
print("a b".isprintable(), "a\n".isprintable()) # True False
print("name_1".isidentifier()) # True
print("1name".isidentifier()) # False
word = "class"
print(word.isidentifier() and not keyword.iskeyword(word)) # FalseClassifying one character at a time
The checks work on a single character too. Looping over a string gives one-character strings, so you can count or filter by class.
text = "Order 66: ship 3 items!"
letters = sum(ch.isalpha() for ch in text)
digits = sum(ch.isdigit() for ch in text)
spaces = sum(ch.isspace() for ch in text)
print(letters, digits, spaces) # 14 3 4
print("".join(ch for ch in "a1b2-c3" if ch.isdigit())) # 123Summing booleans works because True counts as 1. The join call rebuilds a string from the characters that passed the filter, since strings cannot be changed in place.
Filtering with isalnum is a quick way to strip punctuation, but it keeps non-ASCII letters. Add and ch.isascii() if you need ASCII output only.
Common mistakes
- Treating
Falsefrom an empty string as "the text is invalid in some other way". Test for emptiness first if the distinction matters. - Expecting
"-5".isdigit()or"3.14".isdigit()to beTrue. Signs and decimal points are not digits. - Using
isalphato validate names. It rejects hyphens, apostrophes and spaces, so"Anne-Marie"fails. - Forgetting that
isupper()on"HELLO WORLD 2"isTrue. Only letters count. - Assuming
isspaceonly matches the ASCII space. It also matches tabs, newlines and Unicode spaces.
Exercise
A user types "²" into a form field. Which of isdecimal, isdigit and isnumeric return True, and what happens if you call int on it?
Show answer
isdigit and isnumeric return True, and isdecimal returns False. Calling int("²") raises ValueError, because int accepts only decimal digits. This is why isdecimal (with isascii for ASCII only) is the right guard before int.
Exercise
Write a function hasonlyasciilettersand_digits(text) that returns True only for a non-empty string made up of the ASCII letters and digits. Then say what it returns for "abc123", "abc 123", "é1" and "".
Show answer
def hasonlyasciilettersand_digits(text): return text.isascii() and text.isalnum() It returns True for "abc123", False for "abc 123" (the space fails isalnum), False for "é1" (isascii fails) and False for "" (isalnum is False for an empty string).