Python3 String Isdigit
# Python3.x Python3 isdigit() Method
[ Python3 Strings](#)
* * *
## Description
The Python isdigit() method checks whether all characters in the string are digits.
## Syntax
The syntax for the isdigit() method is:
str.isdigit()
## Parameters
* None.
## Return Value
Returns True if all characters in the string are digits, otherwise returns False.
## Example
The following examples demonstrate the usage of the isdigit() method:
## Example
#!/usr/bin/python3
str="123456";
print(str.isdigit())
str="Tutorial example....wow!!!"
print(str.isdigit())
The output of the above examples is:
TrueFalse
The isdigit() method only works correctly for positive integers. It returns incorrect results for negative numbers and decimals.
You can use the following function to solve this problem:
## Example
# Check if it is a number def is_number(s): try: # If the float(s) statement can be executed, return True (string s is a float) float(s)return True except ValueError: # ValueError is a standard Python exception, indicating "invalid argument passed" pass# If a ValueError exception is raised, do nothing (pass: do nothing, often used as a placeholder) try: import unicodedata# Package for handling ASCII codes unicodedata.numeric(s)# Function that converts a string representing a number to a float 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:
TrueTrueTrueTrueTrueFalse
* * Python3 Strings](#)
YouTip