Isdigit method in String Python

In this Python tutorial, I will explain what is isdigit method in String Python. We will see its range, syntax, parameter, and return values. We will also see some demonstrative examples to deep dive into the isdigit() string method and some limitations of its.

Python, a versatile and widely-used programming language, provides numerous built-in methods to simplify the process of string manipulation. Among these is the isdigit() method.

What is the isdigit method in string Python?

The isdigit() method is a built-in function in Python that checks if all the characters in a given string are digits. It returns True if all characters in the string are digits, and False otherwise. It is essential to note that this method does not recognize numbers in a floating-point format or negative numbers as digits.

Basic Syntax:

The syntax of the Python string isdigit method is:

str.isdigit()

Here, str is the Python string on which the operation is going to be held.

Parameter:

The Python isdigit string method does not take any parameters.

Return values:

The return values of the isdigit() method are:

  • True: If all characters in the string are digits.
  • False: If the string contains one or more non-digit characters or if the string is empty.
READ:  How to Take Continuous Input in Python?

Range of the isdigit string method:

Here are some numeral systems and characters recognized by Python isdigit():

  • Arabic Numerals: 0, 1, 2, …, 9
  • Other Numeral Systems:
    • Arabic-Indic Digits: ٠ (0), ١ (1), …, ٩ (9)
    • Extended Arabic-Indic Digits (used in Persian and Urdu): ۰ (0), ۱ (1), …, ۹ (9)
    • Bengali Digits: ০ (0), ১ (1), …, ৯ (9)
    • And similar digits from scripts like Devanagari, Gujarati, Punjabi, Thai, Lao, Tibetan, etc.
  • Special Cases:
    • Superscript and Subscript numbers: ², ³, ₁, ₂, …
    • Some mathematical numbers: ⅕, ⅖, ⅗, …
    • Ancient or historic numeral systems, if they’re represented in Unicode.

Examples Using the string isdigit Method in Python

The isdigit() method in Python is used to determine if all the characters in a string are digits. Its utility is vast, especially in scenarios involving user input validation and data cleansing. Here are situations where using the isdigit() method would be appropriate:

Example-1: Checking the range of isdigit() String method in Python

The range of the isdigit is more vast than just combinations of (0-9) numeric values.

For instance, let’s take numerals named Python list that have different kinds of numeric values.

numerals = ["9", "٩", "۹", "৯", "²", "⅗"]

for num in numerals:
    print(f"'{num}' is digit:", num.isdigit())

The Output is:

'9' is digit: True
'٩' is digit: True
'۹' is digit: True
'৯' is digit: True
'²' is digit: True
'⅗' is digit: True

As discussed in the above section(range of isdigit), the Python isdigit() method has taken all the values from the numerals and returned True.

Python string isdigit() method with different values

This shows the range of the Python isdigit() method in string.

Example-2: User Input Validation using the isdigit Python string method

Let’s write a code that prompts a user to enter their phone number in Python. The isdigit() method ensures the input consists only of digits. The length check ensures it’s a 10-digit number, a standard for US phone numbers.

phone = input("Enter your US phone number: ")
if phone.isdigit() and len(phone) == 10:
    print("Valid US phone number.")
else:
    print("Invalid US phone number.")

The output is:

Enter your US phone number: 1234-56-5245
Invalid US phone number.

or,

Enter your US phone number without dashes: 1234567890
Valid US phone number.

In case-1, the user has entered the number with dashes so, the isdigit function in Python returned False. While in case-2, the user has entered only numbers that are digits so, the string isdigit has returned True.

Python isdigit method in string

This way we can use the isdigit Python function to validate user input.

READ:  Print quotes in Python [6 methods]

Example-3: Data Cleansing with isdigit Python string method

In data science and analytics, before performing operations on datasets, it’s often necessary to cleanse or filter data. If a column should contain only numeric values, the Python string isdigit() can help identify anomalies.

For instance, Suppose we have a list of age data with some anomalies. This code uses the isdigit() Python function to filter out non-numeric entries, ensuring the dataset contains only valid age numbers.

ages = ['25', '30', 'abc', '32']
cleaned_ages = [int(age) for age in ages if age.isdigit()]

print(cleaned_ages)

The output is: Here, we will get a new dataset that will contain only valid age values.

[25, 30, 32]
Isdigit string method in Python

This way we can clean the datasets using the string isdigit method in Python.

Example-4: Using isdigt() Python method in Text Processing

When parsing text documents, if we’re looking to extract or identify numeric sequences, the isdigit() function in Python string can be of use.

Suppose, We have a Book from a library and we got a text that has years written in it. We want to extract all the numeric values from the text(year).

text = "The US declared independence in 1776 ."
numbers = [word for word in text.split() if word.isdigit()]

print(numbers)

The output is: The split() method will split all the characters from the text variable and the for in Python list comprehension will filter only when the if statement is True.

['1776']
Python string isdigit method

This way we can use the isdigit() method in Python for text processing.

Limitations and Points to Note in Python Isdigit method

  • Decimal Numbers: isdigit() Python string method does not recognize decimal numbers as digits. For instance, “4.5” would return False.
  • Negative Numbers: Python s
  • strings with negative numbers, e.g., “-12345”, will return False because of the negative sign.
  • Non-Latin Digits: The method can recognize digits from other numeral systems, like Arabic or Devanagari numerals. So, a string containing “١٢٣” (Arabic numerals for 123) would return True.
READ:  How to Iterate through a Dictionary in Python with Index? [4 Methods]

Conclusion

We have seen what the isdigit method in string Python is, its syntax, parameters, return values, and its range. We have also demonstrated some real-life examples where isdigit() can come in handy and last, we have listed its limitations.

So, The isdigit() method is a handy tool for quickly assessing whether a string consists only of digits. Its applications range from form validations to data cleaning in larger datasets. By understanding its strengths and limitations, developers can effectively leverage this method in their Python programs.

You may also like to read: