How to Check if a String is a Number in Python
Checking if a String is a Number
In Python, you often need to check if a string like "123" or "3.14" actually represents a number before using it in calculations. Here are the most common ways to do it.
Note: All these methods will fail on strings with leading or trailing whitespace like " 123 ". You’ll need to strip the string first with strip() if whitespace is possible in your input.
Using str.isdigit() for Whole Numbers
The simplest way to check if a string is a whole number (like 42 but not 3.14):
# Define some test strings
text1 = "12345"
text2 = "3.14"
text3 = "-42"
text4 = "hello"
# isdigit() returns True only for positive whole numbers
print(text1.isdigit()) # Output: True (it's a valid number)
print(text2.isdigit()) # Output: False (contains a decimal point)
print(text3.isdigit()) # Output: False (contains a minus sign)
print(text4.isdigit()) # Output: False (it's letters, not numbers)
# Practical example: checking user input
user_input = "42"
# Before doing math, check if it's a number
if user_input.isdigit():
result = int(user_input) + 10
print(result) # Output: 52
else:
print("Please enter a whole number")
What isdigit() does: It checks if every character in the string is a digit (0-9). It returns True or False.
Limitation: It only works for positive whole numbers. No decimals, no negative signs, no whitespace.
Using str.isnumeric() for All Numeric Characters
Similar to isdigit(), but also handles Unicode numeric characters:
# Test strings with different number types
text1 = "12345"
text2 = "½" # Unicode fraction
text3 = "十" # Chinese numeral for 10
text4 = "-5"
print(text1.isnumeric()) # Output: True
print(text2.isnumeric()) # Output: True (Unicode numeric)
print(text3.isnumeric()) # Output: True (Chinese numeral)
print(text4.isnumeric()) # Output: False (no negative signs)
When to use: If you’re working with international numbers or Unicode characters.
Using str.isdecimal() for Decimal Digits
This is stricter than isdigit() - it only accepts characters that can be used in a decimal number system:
text1 = "123"
text2 = "½"
text3 = "10.5"
print(text1.isdecimal()) # Output: True
print(text2.isdecimal()) # Output: False (not a decimal digit)
print(text3.isdecimal()) # Output: False (contains a dot)
Using try-except
For real-world programs, the try-except approach is the most reliable. It handles integers, floats, and even numbers with scientific notation:
def is_number(value):
"""
Check if a string represents a valid number.
Handles integers, floats, negative numbers, and scientific notation.
"""
try:
# Try to convert to a float
# If it works, it's a number
float(value)
return True
except ValueError:
# If conversion fails, it's not a number
return False
# Test with various inputs
test_values = ["123", "3.14", "-42", "1.5e10", "hello", "12abc", "", " "]
for value in test_values:
result = is_number(value)
print(f"'{value}' -> {result}")
# Output:
# '123' -> True
# '3.14' -> True
# '-42' -> True
# '1.5e10' -> True (scientific notation works!)
# 'hello' -> False
# '12abc' -> False
# '' -> False
# ' ' -> False
Why this is best: It catches all valid number formats, including:
- Whole numbers:
"42" - Decimals:
"3.14" - Negative numbers:
"-7.5" - Scientific notation:
"2.5e10"
To check for integers only (no decimal points), use int() instead of float():
def is_integer(value):
"""Check if a string is a whole number (no decimal point)."""
try:
num = int(value)
return True
except ValueError:
return False
print(is_integer("42")) # Output: True
print(is_integer("3.14")) # Output: False
print(is_integer("-5")) # Output: True
print(is_integer("hello")) # Output: False
Check if it’s a Float (Decimal Number)
def is_float(value):
"""Check if a string is a decimal number."""
try:
num = float(value)
# Make sure it's not a whole number (that's an int)
return num != int(num)
except ValueError:
return False
print(is_float("3.14")) # Output: True
print(is_float("42")) # Output: False (whole number)
print(is_float("-7.5")) # Output: True
Quick Reference Table
| Method | Use Case | Example Input | Result |
|---|---|---|---|
isdigit() | Positive whole numbers only | "123" | True |
isnumeric() | Numbers including Unicode | "½" | True |
isdecimal() | Decimal digits only | "123" | True |
| try-except | Any valid number | "3.14" or "-42" | True |
Common Mistakes to Avoid
Mistake 1: Using isdigit() on floats
# Wrong way
print("3.14".isdigit()) # Output: False (unexpected!)
# Right way - use try-except
try:
float("3.14")
print("It's a number") # This runs
except ValueError:
print("Not a number")
Mistake 2: Not handling negative numbers
# Wrong way
print("-42".isdigit()) # Output: False (minus sign not allowed)
# Right way - use try-except
try:
float("-42")
print("It's a number") # This runs
except ValueError:
print("Not a number")
Mistake 3: Not handling whitespace
# Wrong way - whitespace causes false negatives
print(" 42".isdigit()) # Output: False
print("42 ".isdigit()) # Output: False
# Right way - strip first
value = " 42 "
if value.strip().isdigit():
print("It's a number")
# Or use try-except (handles whitespace inside the conversion)
try:
float(" 42 ")
print("It's a number") # This runs
except ValueError:
print("Not a number")
Mistake 4: Checking empty strings
# Wrong way - empty string is falsy but not "not a number"
if "": # This is False, but it's not the same check
print("number")
else:
print("not a number") # This runs, but why?
# Right way - explicitly check
try:
float("")
except ValueError:
print("Empty string is not a number") # This runs
Practical Example: Calculator Input Validation
def get_number_from_user(prompt):
"""
Ask user for a number and keep asking until they enter a valid one.
"""
while True:
user_input = input(prompt)
# Try to convert to a number
try:
number = float(user_input)
return number # Exit the function with the valid number
except ValueError:
# If conversion fails, ask again
print(f"'{user_input}' is not a valid number. Please try again.")
# Use the function
age = get_number_from_user("Enter your age: ")
price = get_number_from_user("Enter the price: ")
total = age + price
print(f"Total: {total}")
# Example interaction:
# Enter your age: twenty
# 'twenty' is not a valid number. Please try again.
# Enter your age: 25
# Enter the price: 19.99
# Total: 44.99
Which Method Should You Use?
- Use
isdigit()for simple positive whole numbers when you know the input format - Use try-except for real-world programs that need to handle floats, negatives, and scientific notation
- Always validate user input before using it in calculations
- Strip whitespace from input before checking, or use try-except which handles it more gracefully
The try-except method is the most reliable and should be your default choice unless you have a specific reason to use the string methods.