Skip to content

How to Check If a String Contains Only Digits in Python

Learn how to validate strings for digits-only input in Python using isdigit(), isdecimal(), regex, and handling negatives/decimals with code examples.

Validating text input is a common task in Python, especially when dealing with user inputs like PIN codes, user IDs, or phone numbers. The goal is often to ensure a string consists only of numerical digits (0-9) without any letters, spaces, or punctuation.

This guide explores the built-in string methods isdigit(), isdecimal(), and isnumeric(), explains their subtle differences regarding Unicode and special characters, and provides a robust solution for handling negative numbers and decimals.

Method 1: Using isdigit() (Standard Approach)

The isdigit() method is the most common way to check for digits. It returns True if all characters in the string are digits and there is at least one character. It returns False if the string contains spaces, letters, punctuation, or is empty.

pin_code = "12345"
print(f"'{pin_code}' contains only digits: {pin_code.isdigit()}")

user_id = "123ab"
print(f"'{user_id}' contains only digits: {user_id.isdigit()}")

phone = "123 456"
print(f"'{phone}' contains only digits: {phone.isdigit()}")

Output:

'12345' contains only digits: True
'123ab' contains only digits: False
'123 456' contains only digits: False

Method 2: Handling Negative Numbers and Floats

A common pitfall is assuming isdigit() works for all numbers. It checks for digit characters, not mathematical validity. Therefore, negative signs (-) and decimal points (.) are considered non-digits.

Problem

negative_num = "-123"
float_num = "12.34"

print(f"Negative check: {negative_num.isdigit()}")
print(f"Float check:    {float_num.isdigit()}")

Output:

Negative check: False
Float check:    False

Solution: Try-Except Block

To check if a string represents a valid number (including negatives and floats), try converting it.

def is_valid_number(s):
    try:
        float(s) # Try converting to a number
        return True
    except ValueError:
        return False

print(f"'-123' is a number? {is_valid_number('-123')}")
print(f"'12.34' is a number? {is_valid_number('12.34')}")

Output:

'-123' is a number? True
'12.34' is a number? True

Method 3: isdecimal() vs isdigit() vs isnumeric()

Python provides three methods that seem similar but handle Unicode characters differently.

  1. isdecimal(): Strictest. Only supports characters used to form numbers in base 10 (0-9). Best for int() conversion.
  2. isdigit(): Supports decimals plus compatibility characters like superscripts (²).
  3. isnumeric(): Widest support. Includes fractions (1/2) and Roman numerals.
val_basic = "0"
val_power = "\u00B2" 
val_frac = "\u00BD" 

print(f"{val_basic}: Dec={val_basic.isdecimal()}, Dig={val_basic.isdigit()}, Num={val_basic.isnumeric()}")
print(f"{val_power}: Dec={val_power.isdecimal()}, Dig={val_power.isdigit()}, Num={val_power.isnumeric()}")
print(f"{val_frac}: Dec={val_frac.isdecimal()}, Dig={val_frac.isdigit()}, Num={val_frac.isnumeric()}")

Output:

0: Dec=True, Dig=True, Num=True
²: Dec=False, Dig=True, Num=True
½: Dec=False, Dig=False, Num=True

Method 4: Using Regular Expressions

If you need specific validation rules (e.g., "digits only, exactly 5 characters"), Regular Expressions (re) are more powerful than string methods.

import re

text = "12345"

if re.fullmatch(r'\d+', text):
    print("Regex match: Digits only")
else:
    print("Regex match: Contains other characters")

Output:

Regex match: Digits only

Conclusion

To check if a string contains digits in Python:

  1. Use str.isdigit() for standard checks (PINs, IDs) where only characters 0-9 are allowed.
  2. Use str.isdecimal() if you strictly intend to convert the string to an integer later, avoiding Unicode surprises.
  3. Use try-except float() if you need to validate mathematical numbers containing negatives or decimals.
Navigation