Python3 isdigit() Method

Python3 字符串Python3 Strings


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

Example

The following example demonstrates the isdigit() method:

Example

#!/usr/bin/python3

str = "123456";
print (str.isdigit())

str = "Example example....wow!!!"
print (str.isdigit())

The output of the above example is as follows:

True
False

The isdigit() method is only valid for positive integers; it returns incorrect results for negative numbers and decimals.

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 (string s is a float) float(s) return True except ValueError: # ValueError is a standard Python exception, meaning "invalid argument passed in" pass # If a ValueError exception is raised, do nothing (pass: do nothing, usually 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 float 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 result is:

True
True
True
True
True
False

Python3 字符串Python3 Strings

Other Extensions