Python String isdigit() – ItsMyCode

0
133
Python String isdigit() - ItsMyCode


Python string isdigit() method is a built-in function that returns True if all the characters in a string are digits. Otherwise, it returns false.

What are the valid digits in Python?

In Python, a digit is a character that has the property value.

  • Numeric_Type=Digit 
  • Numeric_Type=Decimal.

The superscript and subscript (usually written using Unicode) are also considered digit characters. So any string containing these characters and decimal is treated as a valid digit in Python.

Note: The roman numerals, currency numerators and fractions (usually written using Unicode) are considered numeric characters and not digits. The isdigit() returns will return False if the string contains roman characters.

isdigit() Syntax

The syntax of isdigit() method is:

string.isdigit()

isdigit() Parameters

The isdigit() method doesn’t take any parameters.

 isdigit() Return value

The isdigit() method returns:

  • True if all characters in the string are digits
  • False if the string has at least one character is non-digit 

Example 1: Working with isdigit() method

# Valid digit, returns true
text1 = "12345"
print(text1.isdigit())

# float, returns false
text2= "12.45"
print(text2.isdigit())

# alphanumeric, returns false
text3= "A123BC "
print(text3.isdigit())

# unicode for 0, returns true
text4="u0030"
print(text4.isdigit())

# fraction, returns false
text5="½"
print(text5.isdigit())

Output

True
False
False
True
False

Example 2: How do I check if a string is Isdigit?

We can use Python string isdigit() method to check if all the characters in a string are digits.

# valid digit
text1 = "12345"
if(text1.isdigit()):
    print("The given string is valid digit")
else:
    print("The given string contains non digit characters")

# u00BD is fraction ½
text2= "u00BD"
if(text2.isdigit()):
    print("The given string is valid digit")
else:
    print("The given string contains non digit characters")

Output

The given string is valid digit
The given string contains non digit characters



Source link

Leave a reply

Please enter your comment!
Please enter your name here