Note

Python - isdigit() - Check if a string contains only digits


Overview of the Python isdigit() Function: Determine if a string contains only digits

string.isdigit() is a built-in method that can be called on string, byte, and bytearray objects. It checks if a given object contains only digits (numeric characters). It returns a boolean value.

Please note that decimal points and negative signs are not considered digits, so they will cause the isdigit() method to return False.

Take a look at the examples below:


Using isdigit() with Strings

string_1 = "12345"
string_2 = "123.45"
string_3 = "-12345"
string_4 = "12a34"
string_5 = "123 45"
string_6 = ""

print(string_1.isdigit()) # True
print(string_2.isdigit()) # False (because of the decimal point)
print(string_3.isdigit()) # False (because of the '-')
print(string_4.isdigit()) # False (because of the character 'a')
print(string_5.isdigit()) # False (because of the space)
print(string_6.isdigit()) # False (because it's empty)

Output:

True
False
False
False
False
False

Using isdigit() with bytes objects

In bytes values, everything works as expected (but only with ASCII literal characters).

bytes_1 = b"12345"
bytes_2 = b"123 45"
bytes_3 = b"12a34"

print(bytes_1.isdigit())  # True
print(bytes_2.isdigit())  # False (because of the space)
print(bytes_3.isdigit())  # False (because of the character 'a')

Output:

True
False
False

Using isdigit() with bytearray objects

And it also works with byte arrays:

bytearray_1 = bytearray(b"12345")
bytearray_2 = bytearray(b"123 45")
bytearray_3 = bytearray(b"12a34")

print(bytearray_1.isdigit())  # True
print(bytearray_2.isdigit())  # False (because of the space)
print(bytearray_3.isdigit())  # False (because of the character 'a')

Output:

True
False
False

Key Points to Remember about the isdigit() Function

  • Returns True for Digits Only: Works with numeric characters (0-9) and returns True if all characters are digits.

  • Case Sensitivity: Alphabetic characters, decimal points, and negative signs result in False.

  • Compatibility: Works with string, bytes, and bytearray objects.

  • Empty Strings: Returns False if called on an empty string or byte-like object.

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: