How to Check If a String Contains Only Digits in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string contains only digits in Python. The lab explores digit strings and introduces the isdigit() method, a built-in Python function that determines if all characters in a string are numerical (0-9).

You will create a Python file, digit_strings.py, and use the isdigit() method to test strings containing only digits and strings containing non-digit characters. By running the script with different string examples, you will observe the True or False output, demonstrating how to effectively identify digit strings in Python.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/strings -.-> lab-559568{{"How to Check If a String Contains Only Digits in Python"}} python/conditional_statements -.-> lab-559568{{"How to Check If a String Contains Only Digits in Python"}} python/for_loops -.-> lab-559568{{"How to Check If a String Contains Only Digits in Python"}} python/build_in_functions -.-> lab-559568{{"How to Check If a String Contains Only Digits in Python"}} end

Explore Digit Strings

In this step, you will learn about digit strings in Python and how to identify them. A digit string is simply a string that contains only numerical characters (0-9). Python provides a built-in method called isdigit() that allows you to easily check if a string consists of only digits.

First, let's create a Python file named digit_strings.py in your ~/project directory using the VS Code editor.

## Create a string containing only digits
digit_string = "12345"

## Use the isdigit() method to check if the string contains only digits
is_digit = digit_string.isdigit()

## Print the result
print(is_digit)

Save the file. Now, let's run the script using the python command:

python ~/project/digit_strings.py

You should see the following output:

True

This indicates that the string digit_string contains only digits.

Now, let's try with a string that contains non-digit characters:

## Create a string containing digits and letters
non_digit_string = "123abc"

## Use the isdigit() method to check if the string contains only digits
is_digit = non_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

This indicates that the string non_digit_string contains characters that are not digits.

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.

Check for Non-Digit Characters

In this step, you will learn how to identify if a string contains any non-digit characters. While the isdigit() method is useful for checking if all characters are digits, sometimes you need to know if there's at least one non-digit character present.

We can achieve this by iterating through the string and checking each character individually. Let's modify the digit_strings.py file in your ~/project directory to implement this.

def has_non_digit(input_string):
  """
  Checks if a string contains any non-digit characters.
  """
  for char in input_string:
    if not char.isdigit():
      return True  ## Found a non-digit character
  return False  ## No non-digit characters found


## Test cases
string1 = "12345"
string2 = "123abc"
string3 = "  123"

print(f"'{string1}' has non-digit characters: {has_non_digit(string1)}")
print(f"'{string2}' has non-digit characters: {has_non_digit(string2)}")
print(f"'{string3}' has non-digit characters: {has_non_digit(string3)}")

Replace the content of digit_strings.py with the above code and save it. Now, let's run the script using the python command:

python ~/project/digit_strings.py

You should see the following output:

'12345' has non-digit characters: False
'123abc' has non-digit characters: True
'  123' has non-digit characters: True

In this script, we define a function has_non_digit() that iterates through each character of the input string. If it finds a character that is not a digit using not char.isdigit(), it immediately returns True. If the loop completes without finding any non-digit characters, it returns False.

This approach allows you to quickly determine if a string contains any characters that are not digits, which can be useful for data validation and other tasks.

Summary

In this lab, you explored how to check if a string contains only digits in Python. You learned that a digit string consists solely of numerical characters (0-9) and that Python provides the built-in isdigit() method for easy identification.

You practiced using the isdigit() method with strings containing only digits, which returned True, and strings containing non-digit characters, which returned False. This demonstrated the method's ability to validate strings and determine if they are composed entirely of digits.