Question
How to Check if a String Is a Number in Python
Question
How can I check whether a string represents a numeric value in Python?
For example, consider this function:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
This works, but it feels a little clunky. Is there a better or more Pythonic way to determine whether a string represents an integer or floating-point number?
Also, if the value comes from user input, it is still a string even if it looks like a number. In that case, how should I validate it before converting it?
Short Answer
By the end of this page, you will understand how Python checks whether a string can be treated as a number, why try/except is a common solution, when float() is appropriate, and what edge cases to watch for when validating user input.
Concept
In Python, a value read from input, a file, or an API often arrives as a string. Even if it looks like 42 or 3.14, Python still treats it as text until you convert it.
The key idea is:
- A string represents a number if Python can successfully convert it to a numeric type.
- A common way to test this is to attempt the conversion and handle failure.
For example:
float("3.14") # works
float("42") # works
float("hello") # raises ValueError
This is why try/except is the standard Python approach. It follows a common Python style called EAFP: Easier to Ask Forgiveness than Permission. Instead of checking every possible format yourself, you try the operation and catch the error if it fails.
Why this matters:
- User input must be validated before calculations.
- Data from CSV files or APIs may contain invalid values.
- Manual checks with string methods often miss important cases like negative numbers, decimals, or scientific notation.
For example, these are all valid for float():
Mental Model
Think of float() like a number scanner at a gate.
- If the string is in a format Python recognizes as numeric, it gets through.
- If not, the scanner rejects it with an error.
Your job is not to inspect every character by hand unless you have special rules. Instead, you let Python's built-in converter do the checking.
Another way to think about it:
- The string is a label on a box.
float()opens the box and checks whether the contents can be treated as a number.- If the box contains non-numeric text, conversion fails.
This is usually better than asking, "Does every character look numeric?" because real numeric formats can include:
- a minus sign:
-5 - a decimal point:
3.14 - exponent notation:
1e9 - surrounding whitespace:
42
Syntax and Examples
The most common pattern is:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Example usage
print(is_number("10")) # True
print(is_number("3.14")) # True
print(is_number("-8")) # True
print(is_number("1e3")) # True
print(is_number("hello")) # False
print(is_number("12a")) # False
If you want the converted number too
Often, you do not just want to check the value. You want to convert it safely.
def parse_number(s):
try:
return (s)
ValueError:
value = parse_number()
value :
(, value)
:
()
Step by Step Execution
Consider this function:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Now trace what happens with this input:
result = is_number("12.5")
print(result)
Step by step
is_number("12.5")is called.- Inside the
tryblock, Python runsfloat("12.5"). - The conversion succeeds, producing
12.5as a float. - No exception happens, so the function returns
True. print(result)displaysTrue.
Now try invalid input:
result = is_number("12.5abc")
print(result)
Step by step
Real World Use Cases
Checking numeric strings is common in real programs.
User input validation
age_text = input("Enter your age: ")
try:
age = int(age_text)
print("Age accepted:", age)
except ValueError:
print("Please enter a whole number.")
Reading CSV or text files
Some columns may contain numbers stored as text.
values = ["10", "20.5", "N/A", "15"]
numbers = []
for item in values:
try:
numbers.append(float(item))
except ValueError:
pass
print(numbers)
Validating API data
An API might send prices as strings:
price_text = "19.99"
try:
price = float(price_text)
print(price * 2)
except ValueError:
print("Invalid price format")
Real Codebase Usage
In real projects, developers usually do more than return True or False. They often combine validation with conversion.
Pattern: validate by converting
def parse_price(text):
try:
return float(text)
except ValueError:
return None
This avoids converting twice.
Pattern: guard clause
def apply_discount(price_text):
try:
price = float(price_text)
except ValueError:
return "Invalid price"
return price * 0.9
The invalid case is handled early, so the rest of the function stays simple.
Pattern: input loop
while True:
text = input("Enter a number: ")
try:
value = (text)
ValueError:
()
(, value)
Common Mistakes
1. Using isdigit() for floats or negative numbers
Broken example:
"-3.5".isdigit()
This returns False, even though -3.5 is a valid number.
Avoid this by using float() or int() in a try block.
2. Checking before converting, then converting again
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
text = "4.2"
if is_number(text):
value = float(text)
This converts the same value twice. In real code, it is often better to convert once and keep the result.
Better:
def parse_number(s):
:
(s)
ValueError:
Comparisons
| Approach | Works for ints | Works for floats | Works for negatives | Works for scientific notation | Best use |
|---|---|---|---|---|---|
str.isdigit() | Yes | No | No | No | Only simple digit-only strings |
int(s) in try/except | Yes | No | Yes | No | Strict integer validation |
float(s) in try/except | Yes | Yes |
Cheat Sheet
# General number check
try:
value = float(s)
except ValueError:
# not numeric
# Integer-only check
try:
value = int(s)
except ValueError:
# not an integer
Quick rules
input()always returns a string.float(s)accepts:"10""-3.5""1e6"" 42 "
int(s)accepts whole numbers only.str.isdigit()is not a general number check.- If you need to reject
nanorinf, usemath.isfinite().
Useful helper
FAQ
Is try/except the Pythonic way to check numeric strings?
Yes. In Python, attempting the conversion and catching errors is a common and recommended pattern.
Should I use isdigit() to check if a string is a number?
Usually no. isdigit() does not handle negative numbers, decimals, or scientific notation.
How do I check if a string is specifically an integer in Python?
Use int() inside a try/except ValueError block.
How do I check if user input is a valid float?
Use float() in a try block. If it raises ValueError, the input is not a valid float.
Does float() accept strings with spaces?
Yes. Surrounding whitespace is allowed, so float(" 3.5 ") works.
Can float() accept values like nan and inf?
Mini Project
Description
Build a small input validator that repeatedly asks the user for a numeric value and rejects invalid entries. This demonstrates safe conversion, error handling, and the difference between accepting any float and accepting only finite numbers.
Goal
Create a program that keeps asking for a number until the user enters a valid finite float.
Requirements
Requirement 1 Requirement 2 Requirement 3
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.