Sling Academy
Home/Python/Python: Check If a String Can Be Converted to a Number

Python: Check If a String Can Be Converted to a Number

Last updated: June 04, 2023

This succinct article shows you several different ways to check whether a string represents a valid integer or float in Python, including negative numbers, decimal numbers, and numbers with exponents. The first two approaches are the best options, while the latter three are also worth knowing.

Using exception handing

This approach is simple, intuitive, and safe. It can handle various types of numbers and doesn’t require external libraries.

Code example:

def is_convertible_to_number(input_str):
    try:
        float(input_str)
        return True
    except ValueError:
        return False

# try it out
print(is_convertible_to_number("123")) # True
print(is_convertible_to_number("123.456")) # True
print(is_convertible_to_number("-2023.01")) # True
print(is_convertible_to_number("123.456.789")) # False

The idea here is to use a try-except block to catch the ValueError exception raised by the conversion function. If no exception is raised, we can totally believe that the string is a valid representation of a number.

Using regular expressions

If you don’t desire to use try-except, then you can use the re module to create a pattern that matches a valid number format and use the match() or fullmatch() methods to check if the string matches the pattern.

In the following example, we’ll use this pattern:

r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$'

Example:

import re

def is_convertible_to_number(input_str):
    pattern = r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$'
    return bool(re.match(pattern, input_str))

# Try it out
print(is_convertible_to_number('123')) # True
print(is_convertible_to_number('123.456')) # True
print(is_convertible_to_number('123.456e+789')) # True
print(is_convertible_to_number('-123.456e-789')) # True
print(is_convertible_to_number('123.456e-')) # False  
print(is_convertible_to_number('1a2b3c')) # False

Using the isdigit() method (check positive integer only)

You you want to check both integers and floats, consider using one of the first two approaches instead.

You can call the isdigit() method on a given string to know all of its characters are digits (0-9). This method returns True if the string is a positive integer, otherwise False.

Example:

s = "123"
print(s.isdigit()) # True

# It doesn't work for negative numbers or floats
s = "-123"
print(s.isdigit()) # False
s = "12.3"
print(s.isdigit()) # False

Using the isnumeric() method

You can use the string isnumeric() method to verify that all the characters in a string are numeric (0-9) or other numeric characters like exponents (², ¾). This method returns True if the string is a numeric value, otherwise False.

Example:

s = "2024"
print(s.isnumeric()) # True
s = "2²2"
print(s.isnumeric()) # True

# This approach doesn't work for negative numbers
s = "-123"
print(s.isnumeric()) # False

# And neither for floating point numbers
s = "12.3"
print(s.isnumeric()) # False

Using the ast.literal_eval() function

ast is a standard module that helps you process trees of the Python abstract syntax grammar. You can use its literal_eval() function to evaluate a string as a Python literal. The function returns the value of the string if it is a valid Python literal, such as an int, float, complex, bool, None, etc. Otherwise, it raises a ValueError or a SyntaxError exception. The code example below will clarify what I am talking about:

import ast

# Function to check if a string is a number
def is_number(s):
    try:
        ast.literal_eval(s) # for int, long, float, complex, etc.
    except (ValueError, SyntaxError):
        return False
    return True

print(is_number('2024')) # True
print(is_number('2.5')) # True
print(is_number('1e-10')) # True
print(is_number('1e-10a')) # False
print(is_number('-2.024')) # False
print(is_number('slingacademy.com')) # False

Next Article: Python: How to Extract Numbers from Text (2 Approaches)

Previous Article: Python: How to get the size of a number (integer, float) in bytes

Series: Python – Numbers & Math Tutorials

Python

You May Also Like

  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs