Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is isdigit() in Python?
2.1.
Syntax of isdigit() in Python
2.2.
Return Type of isdigit() in Python
2.3.
Parameter of isdigit() in Python
2.4.
Time Complexity - O(n)
2.5.
Space Complexity - O(1)
3.
Examples of isdigit() in Python
3.1.
Example 1: Check if a String Consists of Digits only
3.1.1.
CODE
3.2.
Python
3.2.1.
OUTPUT
3.3.
Example 2: Use isdigit() to Verify User Input
3.3.1.
CODE
3.4.
Python
3.4.1.
OUTPUT
3.5.
Example 3: Count the number of digits in a string
3.5.1.
CODE
3.6.
Python
3.6.1.
OUTPUT
3.7.
Example 4: Convert each digit character in a string to an integer
3.7.1.
CODE
3.8.
Python
3.8.1.
OUTPUT
3.9.
Example 5: Remove all non-numeric characters from a string
3.9.1.
CODE
3.10.
Python
3.10.1.
OUTPUT
3.11.
Example 6: Using isdigit for binary string
3.11.1.
CODE
3.12.
Python
3.12.1.
OUTPUT
4.
Applications of isdigit Python
5.
Pros and Cons of the isdigit Python
6.
Errors And Exceptions in isdigit Python
7.
Mistakes When Using isdigit Python
8.
Best Practices for Using isdigit Python
9.
Frequently Asked Questions
9.1.
How do you check if a character is digit in Python?
9.2.
How do you use Isalpha and Isdigit in Python?
9.3.
How do I extract a digit from a string in Python?
9.4.
What does the isdigit() function do in Python?
9.5.
Can isdigit() be used to handle non-integer numeric values?
9.6.
Can the isdigit() method be used on byte strings in Python?
10.
Conclusion
Last Updated: Mar 28, 2024
Easy

Python String isdigit() Method

Introduction

Ever wondered if a string in your Python code is made up entirely of digits? Numbers, numbers everywhere, but are they all valid digits? Python's got your back with the handy isdigit() method.

isdigit python

In this article, we'll discuss the Python String isdigit() Method. We will discuss how it helps you identify those sneaky non-digit characters hiding in your strings. 

What is isdigit() in Python?

isdigit() is a built-in Python function that only checks whether a string has numeric characters. The function returns True if every character in the string is a digit. The function returns False if every character in the string is not a digit. The isdigit() function only works on strings. It raises an AttributeError if the input is not a string. The function can be useful for identifying whether a string represents a numeric value or not. The isdigit() function only considers digits from 0-9. isdigit() can be  combined it with other string functions such as isalpha(), isalnum(), and isspace(). isdigit() function does not perform any conversion or rounding.

Syntax of isdigit() in Python

my_string.isdigit()

Return Type of isdigit() in Python

boolean (True or False)

Parameter of isdigit() in Python

The isdigit() function in Python does not take any parameters. It's a built-in string function that can be called directly on a string object.

Time Complexity - O(n)

This is because the function examines every character in the string to determine whether it is a digit.

Space Complexity - O(1)

The function only stores a small amount of information about the string being evaluated, such as its length and the current position in the string.

Examples of isdigit() in Python

Here are some of the examples of isdigit() function.

Example 1: Check if a String Consists of Digits only

The isdigit() function is used on strings to check if they only contain numeric characters.

example 1

CODE

  • Python

Python

string1 = "98765"
string2 = "Ninja"
# True
print(string1.isdigit())
#False
print(string2.isdigit())

OUTPUT

OUTPUT

The first output line prints True since string1 contains numeric characters only. The second output line prints False since string2 includes alphabetic characters.

Example 2: Use isdigit() to Verify User Input

The isdigit() function helps check user input in cases where only numeric values are allowed.

example 2

CODE

  • Python

Python

#ask the user to enter their age
age = input("Enter your age: ")
#Now check if the input contains only digits using isdigit function
if age.isdigit():
 print("Your age is", age)
else:
 print("Invalid input")

OUTPUT

output

The code prints the user's age if the input value consists of only digits. Otherwise, the code prints an error message.

Example 3: Count the number of digits in a string

To count the number of digits in a string using the isdigit() function in Python. You can iterate over each character in the string and use isdigit() to check if it is a digit.

example 3

CODE

  • Python

Python

# First, input the text you want to analyze
text = "Ninja solved over 400 questions on coding ninjas platform."
#Now count the number of digit characters using the isdigit function
digit_count = sum(1 for char in text if char.isdigit())
print("There are", digit_count, "digits in the text.")

OUTPUT

OUTPUT

This code calculates the number of digits in a string text using a generator expression and the isdigit() function. The sum() function groups the values the generator returns.

Example 4: Convert each digit character in a string to an integer

The code will iterate over each character in the string. It will check if it is a digit using isdigit() and convert it to an integer using the int() function. 

example 4

CODE

  • Python

Python

string = "98766"
digits = [int(char) for char in the string if char.isdigit()]
print(digits)

 

OUTPUT

output

Firstly the code creates a list of integers by iterating over each character in the string. It checks if it is a digit using the isdigit() function. If it is a digit, it converts the character to an integer using the int() function and adds it to the list. 

Example 5: Remove all non-numeric characters from a string

First, the code iterates over each character of the string. If the character is a digit, it adds it to a list of characters. These characters are joined into a new string using the join() function. 

CODE

  • Python

Python

string = "N1I2N3J4A"
only_digits = "".join(char for char in string if char.isdigit())
print(only_digits)

OUTPUT

ouput

This code removes all non-numeric characters from the input string using the isdigit() function.

Example 6: Using isdigit for binary string

The isdigit function will return True if all characters in the string are digits. It will return False if there are any non-digit characters.

example 5

CODE

  • Python

Python

# Firstly, we are defining the binary string
bin_str = "1010100"
# Now let’s check if the string consists of only digits, i.e. (0-9)
if bin_str.isdigit():
   # We are converting the binary string to an integer with base (2 in this case)
   deci_num = int(bin_str, 2)
# Here, we are printing the decimal equivalent of the binary input string
   print("The decimal equivalent of", bin_str, "is", decil_num)
else:
# If the binary string is not valid, we will print an error message
   print(bin_str, "is not a valid binary number")

 

OUTPUT

OUTPUT

In this example, we are checking if the input string is a valid binary string. The output will be an error message if it is not a binary number.

Applications of isdigit Python

  • It can split the text into tokens using numeric characters as delimiters.
     
  • It can be used as part of a password strength-checking algorithm. It ensures that passwords include numerical and non-numerical characters.
     
  • It can be used in natural language processing (NLP) applications to identify and extract numbers from news articles or financial reports.
     
  • It is used for checking the validity of user input and is an essential part of web development. It can help prevent errors and security vulnerabilities in web applications. 

Pros and Cons of the isdigit Python

Here are some pros of isdigit Python :

  • It helps verify input data. Examples are checking if a user has entered a valid phone number or ATM PIN.
     
  • It is faster compared to regular expressions.
     
  • It works with ASCII and Unicode strings.
     
  • It is Easy to understand and use.
     
  • It can be used to remove all non-numeric characters from a string.
     

Here are some cons of isdigit Python :

  • It cannot be used to check for decimal points or negative numbers.
     
  • It is not very flexible.
     
  • It has limited options for dealing with non-numeric characters.
     
  • It requires Python 3.x+ or 2.0+.

Errors And Exceptions in isdigit Python

In the case of the isdigit() method in Python, there aren't any specific errors or exceptions it throws. However, there are a few things to keep in mind:

1. Non-String Input: If you try to use isdigit() on something that's not a string, you'll get a TypeError. This means the method expects a string as input, not a number, list, or any other data type.

2. Unicode Digits: By default, isdigit() only considers basic ASCII digits (0-9). If your string contains digits from other languages (like superscript or subscript characters), these might not be recognized as digits by isdigit().

Here's a breakdown:

  • Correct Usage: "12345".isdigit() will return True because the string contains only digits (0-9).
  • Incorrect Usage: 456.isdigit() will return False because the string contains a decimal point (not a digit).
  • Non-String Input: x = 10 followed by x.isdigit() will cause a TypeError because x is an integer, not a string.
  • Unicode Digits: "¹²³⁴⁵".isdigit() might return False depending on your system's encoding. These are superscript digits, not standard ASCII digits.

Mistakes When Using isdigit Python

Here are some common mistakes to avoid when using the isdigit() function:

  • Need to handle edge cases, such as empty strings or strings consisting entirely of spaces.
     
  • We cannot handle negative numbers, decimal points, or other non-integer numeric values.
     
  • Using isdigit() to check whether a string represents a valid number without additional verification.
     
  • Not casting the input to a string before using isdigit() can result in a TypeError.

Best Practices for Using isdigit Python

Here are some tips for using isdigit() in Python:

  • Always cast input to a string before using isdigit() to avoid errors.
     
  • Be aware of the limitations of isdigit() in handling negative numbers or decimal points.
     
  • Use isdigit() in combination with isnumeric() and isdecimal() to handle edge cases.
     
  • It would help if you considered using regular expressions or other libraries for more advanced verification.
     
  • Use descriptive variable and function names to improve the readability of your code.
     

Also see, Convert String to List Python

Frequently Asked Questions

How do you check if a character is digit in Python?

In Python, you can use the isdigit() method of a string to check if a character is a digit. For example, char.isdigit() returns a boolean indicating whether char is a digit.

How do you use Isalpha and Isdigit in Python?

In Python, isalpha() checks if a string contains only alphabetic characters, and isdigit() checks if a string contains only numeric characters.

How do I extract a digit from a string in Python?

To extract a digit from a string in Python, you can use a loop or list comprehension with isdigit() to filter numeric characters from the string.

What does the isdigit() function do in Python?

Python's isdigit() function checks whether a string contains only numeric characters. It returns a boolean value. If the string includes even one non-digit character, it returns False.

Can isdigit() be used to handle non-integer numeric values?

The isdigit() function cannot handle non-integer values like decimal points. To take non-integer values, you can use other functions such as isdecimal() and isnumeric() with additional methods like try-except blocks or regular expressions.

Can the isdigit() method be used on byte strings in Python?

Yes, the isdigit() method can be used on byte strings in Python. It will only return True if all the byte values (0-255) in the byte string represent valid ASCII digits (48-57). 

Conclusion

The isdigit Python has been thoroughly covered in this article. The article explains the isdigit Python definition, usage, and how it can be used in various cases. To make it easier to learn, several code examples are provided. You can read the articles below to learn more about Python. These articles will help you better understand the concepts related to isdigit Python.
 

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

Happy Coding!

 

Live masterclass