Python String isdigit() and its application

In Python, isdigit() is a built-in method used for string handling.
The isdigit() methods returns “True” if all characters in the string are digits, Otherwise, It returns “False”.
This function is used to check if the argument contains digits such as : 0123456789

Syntax :

string.isdigit()
Parameters:
isdigit() does not take any parameters
Returns :
1.True- If all characters in the string are digits.
2.False- If the string contains 1 or more non-digits.

Examples:

Input : string = '15460'
Output : True

Input : string = '154ayush60'
Output : False
filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code for implementation of isdigit()
   
# checking for digit
string = '15460'
print(string.isdigit())
   
  
string = '154ayush60'
print(string.isdigit())
  

chevron_right


Output:

True
False

Errors And Exceptions

  1. It does not take any arguments, therefore it returns an error if a parameter is passed
  2. Superscript and subscripts are considered digit characters along with decimal characters, therefore, isdigit() returns “True”.
  3. The roman numerals, currency numerators and fractions are not considered to be digits. Therefore, the isdigit() returns “False”

Application : Using ascii values of characters, count and print all the digits using isdigit() function.

Algorithm
1. Initialise a new string and a variable count=0 .
1. Traverse every character using ascii value, check if the character is a digit.
2. If it is a digit, increment the count by 1 and add it to the new string, else traverse to the next character.
3. Print the value of the counter and the new string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to illustrate 
# application of isdigit()
# initialising Empty string
newstring =''
  
  
# Initialising the counters to 0
count = 0
  
# Incrementing the counter if a digit is found 
# and adding the digit to a new string
# Finally printing the count and the new string
  
for a in range(53):
    b = chr(a)
    if b.isdigit() == True:
        count+= 1
        newstring+= b
          
print("Total digits in range :", count)
print("Digits :", newstring)

chevron_right


Output:

Total digits in range : 5
Digits : 01234


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.