All About isdigit() Method in Python
This blog explains isdigit() method in Python. We have explained this concept with the help of examples. Let’s explore!
The isdigit() function in Python is a built-in string handling method that verifies whether all characters in a string are digits, ranging from 0 to 9. This function does not require any arguments and can be applied to strings. It evaluates a condition and returns a Boolean value.
Explore free Python courses
Here you will find information about isdigit() functions, its uses with the help of examples. We will be covering the following sections:
Introduction to isdigit() Method in Python
In Python programming, isdigit() is a built-in function that can be used to check whether all the characters in a given string are digits. This function is particularly useful in situations where it is necessary to validate whether a user input is numerical. Utilizing the isdigit() function ensures that only numbers are entered and processed in your program.
Best-suited Python courses for you
Learn Python with these high-rated online courses
Syntax of isdigit()
The syntax of isdigit() method in Python is given as follows:
string.isdigit()
Parameters of isdigit()
This method does not require any input parameters.
Return Value of isdigit()
The return type of isdigit() function is a Boolean value, which depends on the situation. If all the characters in the string are digits, the function returns True; otherwise, it returns False. However, if the string is empty and contains no digit, the function also returns False.
Exceptions of isdigit()
The isdigit() function does not accept any arguments, so passing a parameter to this function will result in an error.
Additionally, Roman numerals and fractions are not recognized as digits, so if the isdigit() function is used on strings containing these characters, it will return False.
Examples of Using the isdigit() Method in Python
Example 1: Validating User Input
user_input = input(“Enter a number: “)
if user_input.isdigit():
print(“Valid input”)
else:
print(“Invalid input”)
Output:
Enter a number: 45
Valid input
In this example, the isdigit() function is used to validate whether the user has entered a valid number. If the input contains only digits, it is considered valid, and the program proceeds to the next step. Otherwise, the program returns an error message.
Example 2: Extracting numbers from a string
text = "The price of the item is $50.99"
numbers = [int(num) for num in text.split() if num.isdigit()]
print(numbers)
Here, the isdigit() function is used to extract numerical values from a string. The split() function is utilized to break the string into a list of words, and then a list comprehension is used to identify the numerical values. The extracted numbers are then stored in a list.
Example 3: Counting numbers of digits in a string
text = "There are 7 digits in this sentence."
digit_count = sum(1 for char in text if char.isdigit())
print(digit_count)
Output:
1
In this example, the isdigit() function counts the number of digits in a string. The sum() function is used with a generator expression to count the number of characters that satisfy the isdigit() condition.
Example 4: Formatting Phone Numbers
phone_number = "1234567890"
formatted_number = "-".join([phone_number[:3], phone_number[3:6], phone_number[6:]]) if phone_number.isdigit() else "Invalid phone number"
print(formatted_number)
Output:
123-456-7890
In this example, the isdigit() function formats a phone number. If the phone number contains only digits, it is formatted using the join() function and stored in a variable. Otherwise, an error message is displayed.
Example 5: Calculating sum of digits in a number
number = input("Enter a number: ")
if number.isdigit():
digit_sum = sum(int(digit) for digit in number)
print("The sum of digits in the number is:", digit_sum)
else:
print("Invalid input")
Output:
Enter a number: 345
The sum of digits in the number is: 12
This example uses the isdigit() function to check if the input is a valid number. If it is, the sum() function is used with a generator expression to calculate the sum of digits in the number.
Example 6: Creating a PIN number for a user
import random
digits = "0123456789"
pin = "".join(random.choice(digits) for i in range(4))
print("Your PIN is:", pin)
Output:
Your PIN is: 8327
In this example, the isdigit() function is not used directly but is implied in the use of random.choice() function randomly selects digits from the “digits” string. This can be used to generate a PIN number for a user.
Example 7: Checking if a credit card number is valid
credit_card = input("Enter credit card number: ")
if credit_card.isdigit() and len(credit_card) == 16:
print("Valid credit card number")
else:
print("Invalid credit card number")
Output:
Enter credit card number: 1235 45454 6565
Invalid credit card number
In this example, the isdigit() function checks if the input is a 16-digit credit card number. It is considered valid if the input contains only digits and has a length of 16.
Endnotes
The isdigit() function is easy to use and requires no parameters, making it a convenient tool for string handling in Python.
Hope this article was helpful for you. If you wish to learn more about Python and practice Python programming, you can explore related articles here.
FAQs
What is the difference between isdigit() and isnumeric()?
The isdigit() method only recognizes the digits 0-9, while the isnumeric() method recognizes all numeric characters, including fractions, subscripts, superscripts, and other characters from different languages.
What is the return type of isdigit()?
The isdigit() method returns a Boolean value. It returns True if all characters in the string are digits, and False otherwise.
Can isdigit() be used with floating-point numbers?
No, isdigit() cannot be used with floating-point numbers because floating-point numbers contain decimal points and possibly scientific notation, which are not digits.
Can isdigit() be used with negative numbers?
No, isdigit() cannot be used with negative numbers because negative numbers contain a minus sign, which is not a digit.
Can isdigit() be used with Unicode strings?
Yes, isdigit() can be used with Unicode strings because it recognizes Unicode digits as well as ASCII digits.
What happens if isdigit() is used on an empty string?
If isdigit() is used on an empty string, it will return False because an empty string does not contain any digits.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio