Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Check Whether a String Is a Number

Python Check Whether a String Is a Number

Document Object Reference Manual Python3 Examples

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

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 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.

Document Object Reference Manual Python3 Examples