W3docs

How do I check if a string represents a number (float or int)?

There are several ways to measure elapsed time in Python.

There are several ways to check if a string represents a number (float or int) in Python. Here are three common options:

  1. try/except with float(): This is the most reliable method. You attempt to convert the string to a float inside a try block. If it succeeds, the string is a valid number. If it raises a ValueError, it is not.
  2. try/except with int(): Similar to the above, but specifically checks for integer representations. This will return False for strings like "3.14".
  3. str.isdigit() or str.isnumeric(): These string methods check if all characters are digits. Note that isnumeric() accepts Unicode numerals (like superscripts ²), while isdigit() is stricter. However, neither handles negative numbers, decimals, or scientific notation, so they are less reliable for general number checking.

Here's an example of how you could use try/except with float() to check if a string represents a number:

Check if a string represents a number using try/except

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

# Test the function
print(is_number("123"))      # True
print(is_number("3.14"))     # True
print(is_number("-42"))      # True
print(is_number("abc"))      # False
print(is_number("12.3.4"))   # False

Note: The float() approach also handles edge cases like plus signs (+123) and scientific notation (1.23e4). You can adapt this pattern to specifically check for integers by using int(s) instead of float(s), or combine both checks depending on your exact requirements.