Easy Tutorial
❮ Python Json Python Func Complex ❯

Python Check if String is a Number

Python3 Examples

The following example creates a custom function is_number() to check if a string is a number:

Example (Python 3.0+)

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.tutorialpro.org

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

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False

# Test strings and numbers
print(is_number('foo'))   # False
print(is_number('1'))     # True
print(is_number('1.3'))   # True
print(is_number('-1.37')) # True
print(is_number('1e3'))   # True

# Test Unicode
# Arabic 5
print(is_number('٥'))  # True
# Thai 2
print(is_number('๒'))  # True
# Chinese number
print(is_number('四')) # True
# Copyright symbol
print(is_number('©'))  # False

We can also use an embedded if statement to achieve this:

Executing the above code outputs the following results:

False
True
True
True
True
True
True
True
False

More Methods

Python isdigit() method checks if the string consists only of digits.

Python isnumeric() method checks if the string consists only of numeric characters. This method is only for unicode objects.

Python3 Examples

❮ Python Json Python Func Complex ❯