If you want to check if a Python string contains only numbers, such as a ZIP code or a PIN, the short answer is s.isdigit(). It mostly works.
The catch is that isdigit() says True for characters most people wouldn’t call numbers, such as ² and full-width digits pasted from a phone keyboard. An empty cell quietly returns False, too.
Quick answer: call s.isdigit(). It returns True when the string has at least one character and every character is a digit. For plain 0-9 only, add isascii(). Save this as quick.py and run python quick.py in a terminal:
zip_code = "60614"
print(zip_code.isdigit()) # True
print(zip_code.isascii() and zip_code.isdecimal()) # True, 0-9 only
In this tutorial, I’ll show you how to check if a Python string contains only numbers, test a single character, spot a string that contains any number, and validate whole pandas columns. Each output below comes from a real Python 3.12.5 run.
Check if a Python String Contains Only Digits with isdigit()
New to running Python files? Here’s my setup for every example:
- Create a folder such as
C:\pyguidesand open it in VS Code or Notepad. - Make a new file named
zip_check.py, paste the code below and save it. - Open Command Prompt in that folder and run
python zip_check.py. - Compare your output with the screenshot.
Here are six ZIP code values from the store’s export. Save them as zip_check.py and run python zip_check.py in Command Prompt:
zips = ["60614", "6061", "60614-2201", " 60614", ""]
for z in zips:
print(f"{z!r:>14} -> {z.isdigit()}")
Output:
'60614' -> True
'6061' -> True
'60614-2201' -> False
' 60614' -> False
'' -> False

60614 and 6061 pass, the ZIP+4 with a dash, the leading space and the empty string all fail.A dash, a space or a decimal point makes isdigit() return False. 6061 passes because Python checks characters, not length, so add len(z) == 5 when length matters.
Want every option the method has? My isdigit() method tutorial goes through it one case at a time.
Why Does isdigit() Accept ² in Python?
isdigit() follows Unicode, so superscripts, Arabic-Indic digits and full-width digits all count. For ZIP codes, PINs and account numbers I want plain 0-9, which is what isascii() plus isdecimal() gives you.
Save this as ascii_check.py and run python ascii_check.py in Command Prompt:
samples = ["60614", "60614", "²", "٣", "4821"]
for s in samples:
strict = s.isascii() and s.isdecimal()
print(f"{s!r:>9} isdigit={s.isdigit()!s:<5} "
f"0-9 only={strict}")
Output:
'60614' isdigit=True 0-9 only=True
'60614' isdigit=True 0-9 only=False
'²' isdigit=True 0-9 only=False
'٣' isdigit=True 0-9 only=False
'4821' isdigit=True 0-9 only=True
Only 60614 and 4821 pass the strict check. The risky one is ²: isdigit() says True, yet Python’s int("²") raises ValueError.
The three methods are compared side by side in the isdecimal() method in Python, and checking if a string is ASCII covers the other half of the test.
Match Only Numbers with a Python Regular Expression
A regex helps when you also need a length, like a 4-digit PIN. Use re.fullmatch() with [0-9]+; the common ^\d+$ with re.match() has a trap.
Save this as pin_regex.py and run python pin_regex.py in Command Prompt:
import re
pins = ["4821", "48a1", "4821\n", "\u0663" * 4, ""]
for pin in pins:
loose = bool(re.match(r"^\d+$", pin))
strict = bool(re.fullmatch(r"[0-9]+", pin))
print(f"{pin!a:<26} match ^\\d+$={loose!s:<5} "
f"fullmatch [0-9]+={strict}")
Output:
'4821' match ^\d+$=True fullmatch [0-9]+=True
'48a1' match ^\d+$=False fullmatch [0-9]+=False
'4821\n' match ^\d+$=True fullmatch [0-9]+=False
'\u0663\u0663\u0663\u0663' match ^\d+$=True fullmatch [0-9]+=False
'' match ^\d+$=False fullmatch [0-9]+=False
![python regex fullmatch only digits vs match newline command prompt Command Prompt output comparing Python re.match with ^\d+$ and re.fullmatch with [0-9]+ on PIN strings, including one with a trailing newline](https://pythonguides.com/wp-content/uploads/2026/11/python-regex-fullmatch-only-digits-vs-match-newline-command-prompt.png)
^\d+$ accepts '4821\n' and the Arabic-Indic \u0663 digits, while fullmatch with [0-9]+ rejects both.How does this code work? $ also matches just before a trailing newline, so a line read from a file slips through.
\d also matches any Unicode digit unless you pass re.ASCII. For a 4-digit PIN write [0-9]{4}. More patterns are in my regular expressions in Python tutorial.
How to Check if a Character Is a Number in Python
A character is a one-character string, so the same method works. Loop over a member ID to test each one.
Save this as char_check.py and run python char_check.py in Command Prompt:
member_id = "PX-2026-7"
for ch in member_id:
print(f"{ch!r}: {ch.isdigit()}")
print("Digits only:", "".join(c for c in member_id if c.isdigit()))
Output:
'P': False
'X': False
'-': False
'2': True
'0': True
'2': True
'6': True
'-': False
'7': True
Digits only: 20267

PX-2026-7 prints True or False, and the digits joined together give 20267.You can also write ch in string.digits, which only accepts 0-9. To count the matches instead, see how to count numbers in a string in Python.
Check if a String Contains a Number (Any Digit)
Sometimes the question flips: does a Python string contain a number anywhere? For pet names, any() with isdigit() answers it in one Python line.
Save this as contains_number.py and run it with python contains_number.py:
import re
names = ["Rex", "Rex2", "Bella 3rd", "Max"]
for name in names:
has_num = any(ch.isdigit() for ch in name)
print(f"{name!r:>12} contains a number: {has_num} "
f"re.search: {bool(re.search(r'[0-9]', name))}")
Output:
'Rex' contains a number: False re.search: False
'Rex2' contains a number: True re.search: True
'Bella 3rd' contains a number: True re.search: True
'Max' contains a number: False re.search: False
Rex2 and Bella 3rd contain a number; Rex and Max don’t. To pull the numbers out, read finding a number in a string in Python.
Validate Digit-Only Columns in pandas
The real export had thousands of rows, so I checked whole columns with the pandas .str accessor.
Save this as zip_pandas.py and run python zip_pandas.py in Command Prompt:
import pandas as pd
df = pd.DataFrame({
"customer": ["Emily", "James", "Olivia", "Noah"],
"zip": ["60614", "6061", "60614-2201", None],
})
df["all_digits"] = df["zip"].str.isdigit()
df["valid_zip"] = df["zip"].str.fullmatch(r"[0-9]{5}")
print(df)
print("Bad rows:", df.loc[~df["valid_zip"], "customer"].tolist())
Output:
customer zip all_digits valid_zip
0 Emily 60614 True True
1 James 6061 True False
2 Olivia 60614-2201 False False
3 Noah NaN False False
Bad rows: ['James', 'Olivia', 'Noah']

60614 is a valid 5-digit ZIP; James, Olivia and the missing value for Noah are flagged.In pandas 3 the missing ZIP returns False, so it lands in the bad rows. It works on Excel data too; see Python in Excel if your data lives there.
Allow Dashes, Spaces or a Minus Sign Before the Check
Phone numbers arrive as (312) 555-0147, so a strict check fails every one. Keep the digits first, then check the length. For a leading sign, strip it before calling isdigit().
Save this as clean_digits.py and run python clean_digits.py in Command Prompt:
phones = ["(312) 555-0147", "312.555.0199", "+1 312 555 0123"]
for raw in phones:
digits = "".join(ch for ch in raw if ch.isdigit())
print(f"{raw!r:>18} -> {digits} ({len(digits)} digits)")
amount = "-42"
print(amount.isdigit(), amount.lstrip("+-").isdigit())
Output:
'(312) 555-0147' -> 3125550147 (10 digits)
'312.555.0199' -> 3125550199 (10 digits)
'+1 312 555 0123' -> 13125550123 (11 digits)
False True
All three phones become plain digits; the +1 country code makes the last one 11 digits long. -42 passes once the sign is stripped.
Need to know whether a Python string is a number with a decimal point? Read checking if a string is an integer or float.
Python Digit-Check Mistakes I Still See
- Calling isdigit() on an int: it’s a string method, so
5.isdigit()fails. Convert withstr()first. - Forgetting empty strings:
"".isdigit()is False,, so check blanks first for a clearer message. - Trusting ^\d+$: it accepts a trailing newline; use
re.fullmatch(r"[0-9]+", s). - Using it for user input: try
int()instead, as in checking if input is a number in Python.
Once your digit checks work, these Python string posts are worth a look:
- isalpha() in Python
- Check for only letters, numbers and underscores in Python
- Check if a variable is an integer in Python
- Tkinter Entry that allows only numbers
Questions About Digit-Only Python Strings
How do I check if a string contains only numbers in Python?
Call s.isdigit(). It returns True when the string isn’t empty and every character is a digit.
How do I check if a character is a number in Python?
Use ch.isdigit() or ch in string.digits for plain 0-9 only.
How do I check if a string contains a number in Python?
Use any(ch.isdigit() for ch in s) or re.search(r"[0-9]", s).
Why does isdigit() return False for a negative number?
The minus sign isn’t a digit. Strip it with s.lstrip("+-") first, or convert with int().
Does isdigit() return True for an empty string?
No. "".isdigit() returns False, and so do isdecimal() and isnumeric().
Where is str.isdigit() documented?

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn