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

Python3 isdigit() Method

Python3 isdigit() Method

Python3 Strings Python3 Strings


Description

The Python isdigit() method checks whether a string consists only of digits.

Syntax

Syntax of the isdigit() method:


str.isdigit()

Parameters

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"

;

print

(

str

.

isdigit

(

)

)

str

=

"Runoob example....wow!!!"

print

(

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

print

(

is_number

(

1

)

)

print

(

is_number

(

1.0

)

)

print

(

is_number

(

0

)

)

print

(

is_number

(

2

)

)

print

(

is_number

(

2.0

)

)

print

(

is_number

(

"

abc

"

)

)

The output is:

True
True
True
True
True
False

Python3 Strings Python3 Strings