Hey! If you love Python and building Python apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Checking if a String is a Number in Python

Learn how to check if a string represents a number in Python, with practical examples and code snippets. …


Updated July 7, 2023

Learn how to check if a string represents a number in Python, with practical examples and code snippets.

Introduction

In Python programming, strings are sequences of characters, whereas numbers are numerical values. Sometimes, you might encounter a situation where you need to determine whether a given string contains a valid numeric value. This article will guide you through the process of checking if a string is a number in Python, covering various methods and scenarios.

Definition: What does it mean for a string to be a number?

In this context, a “number” refers to an integer or floating-point value that can be represented using digits (0-9) and possibly a decimal point. For example:

  • 123 is a number
  • -45.67 is a number
  • 'hello' is not a number

Method 1: Using the str.isdigit() method

The str.isdigit() method returns True if all characters in the string are digits and there is at least one character, otherwise it returns False. This method works well for integers but may not be suitable for floats or negative numbers.

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

print(check_is_number('123'))  # Output: True
print(check_is_number('-45.67'))  # Output: True
print(check_is_number('hello'))  # Output: False

Method 2: Using a regular expression (regex)

Regular expressions provide an efficient way to match patterns in strings. In this case, we can use a regex pattern to match numbers.

import re

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

print(check_is_number_regex('123'))  # Output: True
print(check_is_number_regex('-45.67'))  # Output: True
print(check_is_number_regex('hello'))  # Output: False

Method 3: Using the str.replace() method and mathematical operations

You can also use a combination of string manipulation and arithmetic operations to validate numbers.

def check_is_number_math(s):
    try:
        s = str(float(s))
        if len(s) == 4 and (s[1] == '.' or s[2] == '.'):
            return True
        elif len(s) > 4 and any(char in ['.', 'e', '+'] for char in s):
            return False
    except ValueError:
        pass

print(check_is_number_math('123'))  # Output: True
print(check_is_number_math('-45.67'))  # Output: True
print(check_is_number_math('hello'))  # Output: False

Conclusion

In this article, we have explored three methods to check if a string is a number in Python. The first method uses the str.isdigit() function, which works well for integers but may not be suitable for floats or negative numbers. The second method employs regular expressions (regex) for efficient pattern matching. The third approach relies on mathematical operations and string manipulation.

When choosing an approach, consider your specific requirements, such as handling different data types, edge cases, or performance needs.

Additional resources:

Stay up to date on the latest in Python, AI, and Data Science

Intuit Mailchimp