Python Check if String is a Number
The following example creates a custom functionis_number()to determine whether a string is a number:
Example (Python 3.0+)
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.example.com
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 numerals
print(is_number('four')) # True
# Copyright symbol
print(is_number('©')) # False
We can also use embedded if statements to achieve this:
Executing the above code produces the output:
False True True True True True True True False
More Methods
Python isdigit() The method checks whether the string consists only of digits.
Python isnumeric() The method checks whether the string consists only of digits. This method is only for unicode objects.
Other Extensions
Python3 Examples