Python String isdigit() Method
Last Updated :
23 Feb, 2023
Python String isdigit() method returns “True” if all characters in the string are digits, Otherwise, It returns “False”.
Python String isdigit() Method Syntax
Syntax: string.isdigit()
Parameters: isdigit() does not take any parameters
Returns:
- True – If all characters in the string are digits.
- False – If the string contains 1 or more non-digits.
Time Complexity: O(1)
Auxiliary Space: O(1)
Python String isdigit() Method Example
Output:
True
Example 1: Basic Usage
Python code for implementation of isdigit()
Python3
string = '15460'
print (string.isdigit())
string = '154ayush60'
print (string.isdigit())
|
Output:
True
False
Example 2: Practical Implementation
Application: Using ASCII values of characters, count and print all the digits using isdigit() function.
Algorithm:
- Initialize a new string and a variable count=0.
- Traverse every character using ASCII value, check if the character is a digit.
- If it is a digit, increment the count by 1 and add it to the new string, else traverse to the next character.
- Print the value of the counter and the new string.
Python3
newstring = ''
count = 0
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)
|
Output:
Total digits in range : 5
Digits : 01234
In Python, superscript and subscripts (usually written using Unicode) are also considered digit characters. Hence, if the string contains these characters along with decimal characters, isdigit() returns True. The Roman numerals, currency numerators, and fractions (usually written using Unicode) are considered numeric characters but not digits. The isdigit() returns False if the string contains these characters. To check whether a character is a numeric character or not, you can use isnumeric() method.
Example 3: String Containing digits and Numeric Characters
Python3
s = '23455'
print (s.isdigit())
s = '\u00B23455'
print (s.isdigit())
s = '\u00BD'
print (s.isdigit())
|
Output:
True
True
False
Errors And Exceptions:
- It does not take any arguments, therefore it returns an error if a parameter is passed
- Superscript and subscripts are considered digit characters along with decimal characters, therefore, isdigit() returns “True”.
- The Roman numerals, currency numerators, and fractions are not considered to be digits. Therefore, the isdigit() returns “False”
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...