Python3 isdigit() Method
Description
The Python isdigit() method checks whether a string consists only of digits.
Syntax
Syntax of the isdigit() method:
str.isdigit()
Parameters
- none.
Return Value
Returns True if the string contains only digits, otherwise False.
Example
The following example demonstrates the isdigit() method:
Example
#!/usr/bin/python3
str
=
"123456"
;
(
str
.
isdigit
(
)
)
str
=
"Runoob example....wow!!!"
(
str
.
isdigit
(
)
)
The output of the above example is:
True
False
The isdigit() method only works for positive integers; negative numbers and decimals return incorrect results.
You can use the following function to solve this:
Example
Determine whether it is a number
def
is_number
(
s
)
:
try
:
If the float(s) statement can be run, return True (the string s is a floating-point number)
float
(
s
)
return
True
except
ValueError
:
ValueError is a standard Python exception meaning "an invalid argument was passed"
pass
If a ValueError exception is raised, do nothing (pass: does nothing, generally used as a placeholder statement)
try
:
import
unicodedata
Package for handling ASCII codes
unicodedata
.
numeric
(
s
)
A function that converts a string representing a number into a floating-point number and returns it
return
True
except
(
TypeError
,
ValueError
)
:
pass
return
False
(
is_number
(
1
)
)
(
is_number
(
1.0
)
)
(
is_number
(
0
)
)
(
is_number
(
2
)
)
(
is_number
(
2.0
)
)
(
is_number
(
"
abc
"
)
)
The output is:
True
True
True
True
True
False
Python3 Strings