Python Check Whether a String Is a Number
The following example creates a custom function is_number() to determine whether a string is a number:
Example (Python 3.0+)
-- coding: UTF-8 --
Filename : test.py
author by : www.runoob.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
(
is_number
(
'
foo
'
)
)
False
(
is_number
(
'
1
'
)
)
True
(
is_number
(
'
1.3
'
)
)
True
(
is_number
(
'
-1.37
'
)
)
True
(
is_number
(
'
1e3
'
)
)
True
Test Unicode
Arabic 5
(
is_number
(
'
٥
'
)
)
True
Thai 2
(
is_number
(
'
๒
'
)
)
True
Chinese numerals
(
is_number
(
'
Four
'
)
)
True
Copyright symbol
(
is_number
(
'
©
'
)
)
False
We can also implement this with nested if statements:
The output of the code above is:
False
True
True
True
True
True
True
True
False
More methods
Python isdigit()The method checks whether a string consists only of digits.
Python isnumeric()The method checks whether a string consists only of digits. This method applies only to unicode objects.
Python3 Examples