The Python string isdigit() function checks if all characters in a string are digits and returns a boolean value.
s1 = "123"
s2 = "hello"
print(s1.isdigit())
print(s2.isdigit())
#Output:
True
False
When working with strings in Python, the ability to make checks and determine certain properties easily is very valuable.
One such case is if you want to check if all characters in a string are digits in Python.
The Python string isdigit() function checks if all characters in a string are digits and returns a boolean value.
If all characters are digits, then isdigit() returns True. If at least one character is not a digit, i.e. a letter or symbol, then isdigit() returns False.
Using isdigit() can be useful for data validation if you want to check if a string is an integer or if it has non-numeric characters.
Below are some examples showing you how to use isdigit() in Python to check if a string is made up of all digits.
s1 = "123"
s2 = "hello"
s3 = "hello123"
print(s1.isdigit())
print(s2.isdigit())
print(s3.isdigit())
#Output:
True
False
False
Using isdigit() to Check if String Contains Only Numbers in Python
There are a few special cases you need to be aware of when using isdigit(). These special cases arise when your strings have unicode characters.
For example, superscript and subscripts are considered digit characters. On the other hand, numeric characters, such as roman numerals, currency numerators and fractions, are not digit characters.
Below show some more examples of how isdigit() treats these special cases when your string contain unicode characters.
s2 = "u00B123"
s3 = "u00BC"
print(s2)
print(s3)
print(s2.isdigit())
print(s3.isdigit())
#Output:
²123
¼
True
False
Hopefully this article has been useful for you to learn how to use the Python isdigit() function.