0
0
PythonHow-ToBeginner · 3 min read

How to Check if String is a Valid Number in Python

To check if a string is a valid number in Python, use float() inside a try-except block to catch errors if conversion fails. Alternatively, use string methods like str.isdigit() for integers, but float() is more flexible for decimals and negatives.
📐

Syntax

Use the float() function to try converting a string to a number. Wrap it in a try-except block to handle invalid strings without crashing.

  • try: attempts to convert the string
  • except ValueError: catches the error if conversion fails
python
try:
    number = float(string)
    # string is a valid number
except ValueError:
    # string is not a valid number
💻

Example

This example shows how to check if different strings are valid numbers using float() and try-except. It prints whether each string is a valid number or not.

python
def is_valid_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

samples = ["123", "45.67", "-8.9", "abc", "12a", "", "0"]

for sample in samples:
    if is_valid_number(sample):
        print(f"'{sample}' is a valid number")
    else:
        print(f"'{sample}' is NOT a valid number")
Output
'123' is a valid number '45.67' is a valid number '-8.9' is a valid number 'abc' is NOT a valid number '12a' is NOT a valid number '' is NOT a valid number '0' is a valid number
⚠️

Common Pitfalls

Using str.isdigit() only works for positive integers without decimals or signs, so it fails for floats and negatives. Also, empty strings or strings with spaces cause errors if not handled.

Always prefer float() with try-except for robust checking.

python
s = "-123"

# Wrong way: isdigit() fails for negative numbers
print(s.isdigit())  # Output: False

# Right way: use try-except with float
try:
    float(s)
    print("Valid number")
except ValueError:
    print("Invalid number")
Output
False Valid number
📊

Quick Reference

Summary tips for checking if a string is a valid number in Python:

  • Use float() inside try-except to handle all numeric formats including negatives and decimals.
  • str.isdigit() only works for positive integers without signs or decimals.
  • Empty strings and strings with spaces are not valid numbers.
  • For integers only, you can use int() with try-except.

Key Takeaways

Use float() with try-except to check if a string is a valid number in Python.
str.isdigit() only works for positive integers without decimals or signs.
Try-except blocks prevent your program from crashing on invalid input.
Empty strings and strings with letters or spaces are not valid numbers.
For integer-only checks, use int() with try-except similarly.