Use isdigit() Method
In the previous step, you learned the basics of digit strings and how to use the isdigit()
method. In this step, we will explore the isdigit()
method in more detail and see how it can be used with different types of strings.
The isdigit()
method is a string method in Python that returns True
if all characters in the string are digits, and False
otherwise. It's a simple yet powerful tool for validating user input or processing data that should contain only numbers.
Let's continue using the digit_strings.py
file in your ~/project
directory. We'll modify the script to test the isdigit()
method with various strings.
First, let's test with an empty string:
## Create an empty string
empty_string = ""
## Use the isdigit() method to check if the string contains only digits
is_digit = empty_string.isdigit()
## Print the result
print(is_digit)
Replace the content of digit_strings.py
with the above code and save it. Run the script again:
python ~/project/digit_strings.py
You should see the following output:
False
An empty string does not contain any digits, so isdigit()
returns False
.
Next, let's test with a string containing only spaces:
## Create a string containing only spaces
space_string = " "
## Use the isdigit() method to check if the string contains only digits
is_digit = space_string.isdigit()
## Print the result
print(is_digit)
Replace the content of digit_strings.py
with the above code and save it. Run the script again:
python ~/project/digit_strings.py
You should see the following output:
False
A string containing only spaces is not considered a digit string, so isdigit()
returns False
.
Finally, let's test with a string containing Unicode digits:
## Create a string containing Unicode digits
unicode_digit_string = "ไธไบไธ" ## These are Chinese numerals
## Use the isdigit() method to check if the string contains only digits
is_digit = unicode_digit_string.isdigit()
## Print the result
print(is_digit)
Replace the content of digit_strings.py
with the above code and save it. Run the script again:
python ~/project/digit_strings.py
You should see the following output:
False
The isdigit()
method only returns True
for ASCII digits (0-9), not for other Unicode characters that represent numbers.