Skip to main content

How to check if a string contains only digits in Python

How to check if a string contains only digits in Python.

Here's a step-by-step tutorial on how to check if a string contains only digits in Python:

  1. Start by defining a function, let's call it is_digits_only, that takes a string as an input parameter.

  2. Inside the function, use the isdigit() method to check if each character in the string is a digit.

  3. To do this, iterate through each character in the string using a for loop.

  4. Inside the loop, use an if statement to check if the character is not a digit. If you find any non-digit character, return False to indicate that the string contains non-digit characters.

  5. If the loop completes without finding any non-digit characters, return True to indicate that the string contains only digits.

Here's an example implementation of the is_digits_only function:

def is_digits_only(string):
for char in string:
if not char.isdigit():
return False
return True

Now, let's test the function with some examples:

print(is_digits_only("12345"))  # Output: True
print(is_digits_only("12abc")) # Output: False
print(is_digits_only("9876543210")) # Output: True
print(is_digits_only("0")) # Output: True
print(is_digits_only("")) # Output: True (an empty string is considered to contain only digits)

In this example, we test the function is_digits_only with different strings. The expected output is shown as comments next to each test case.

That's it! You now have a function that can check if a string contains only digits in Python.