How to Check If a Character Is a Digit in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a character is a digit in Python using the isdigit() method. This skill is crucial for validating user input and processing numerical data.

The lab guides you through creating a digit_check.py file, assigning a character to a variable, and using the isdigit() method to determine if it's a digit. You'll then modify the character and rerun the script to observe the different outputs, demonstrating how to differentiate between digit and non-digit characters.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) 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-559498{{"How to Check If a Character Is a Digit in Python"}} python/conditional_statements -.-> lab-559498{{"How to Check If a Character Is a Digit in Python"}} python/for_loops -.-> lab-559498{{"How to Check If a Character Is a Digit in Python"}} python/build_in_functions -.-> lab-559498{{"How to Check If a Character Is a Digit in Python"}} end

Explore Digit Characters

In this step, you will learn how to identify digit characters in Python. Python provides built-in methods to check if a character is a digit. Understanding how to work with digit characters is essential for validating user input, processing numerical data, and building robust applications.

Let's start by creating a Python file named digit_check.py in your ~/project directory using the VS Code editor.

## Create a file named digit_check.py in ~/project

Now, open the digit_check.py file in the editor and add the following code:

## ~/project/digit_check.py
character = '5'

## Check if the character is a digit
if character.isdigit():
    print(f"'{character}' is a digit.")
else:
    print(f"'{character}' is not a digit.")

In this code:

  • We define a variable character and assign it the value '5'.
  • We use the isdigit() method to check if the character is a digit.
  • If isdigit() returns True, we print a message indicating that the character is a digit. Otherwise, we print a message indicating that it is not a digit.

To run the script, open your terminal and navigate to the ~/project directory:

cd ~/project

Then, execute the Python script using the python command:

python digit_check.py

You should see the following output:

'5' is a digit.

Now, let's modify the digit_check.py file to check a different character. Change the value of the character variable to 'A':

## ~/project/digit_check.py
character = 'A'

## Check if the character is a digit
if character.isdigit():
    print(f"'{character}' is a digit.")
else:
    print(f"'{character}' is not a digit.")

Save the changes and run the script again:

python digit_check.py

This time, you should see the following output:

'A' is not a digit.

This demonstrates how the isdigit() method can be used to differentiate between digit characters and non-digit characters.

Use isdigit() Method

In the previous step, you learned the basics of identifying digit characters using the isdigit() method. In this step, we will explore more advanced uses of the isdigit() method, including iterating through strings and checking each character.

Let's modify the digit_check.py file in your ~/project directory to iterate through a string and check each character.

Open the digit_check.py file in the VS Code editor and add the following code:

## ~/project/digit_check.py
input_string = "123abc456"

## Iterate through the string and check each character
for character in input_string:
    if character.isdigit():
        print(f"'{character}' is a digit.")
    else:
        print(f"'{character}' is not a digit.")

In this code:

  • We define a variable input_string and assign it the value "123abc456".
  • We use a for loop to iterate through each character in the string.
  • Inside the loop, we use the isdigit() method to check if the current character is a digit.
  • We print a message indicating whether each character is a digit or not.

To run the script, open your terminal and navigate to the ~/project directory:

cd ~/project

Then, execute the Python script using the python command:

python digit_check.py

You should see the following output:

'1' is a digit.
'2' is a digit.
'3' is a digit.
'a' is not a digit.
'b' is not a digit.
'c' is not a digit.
'4' is a digit.
'5' is a digit.
'6' is a digit.

This demonstrates how you can use the isdigit() method to process strings and identify digit characters within them. This is particularly useful for data validation and parsing tasks.

Validate Character Length

In this step, you will combine the isdigit() method with length validation to ensure that an input string meets specific criteria. This is a common requirement in many applications, such as validating user input for phone numbers or zip codes.

Let's modify the digit_check.py file in your ~/project directory to validate that an input string contains only digits and has a specific length.

Open the digit_check.py file in the VS Code editor and add the following code:

## ~/project/digit_check.py
input_string = "12345"
expected_length = 5

## Check if the string contains only digits and has the expected length
if len(input_string) == expected_length and input_string.isdigit():
    print(f"The string '{input_string}' is valid.")
else:
    print(f"The string '{input_string}' is invalid.")

In this code:

  • We define a variable input_string and assign it the value "12345".
  • We define a variable expected_length and assign it the value 5.
  • We use the len() function to get the length of the input string.
  • We use the isdigit() method to check if the string contains only digits.
  • We combine these checks using the and operator to ensure that both conditions are met.
  • We print a message indicating whether the string is valid or invalid.

To run the script, open your terminal and navigate to the ~/project directory:

cd ~/project

Then, execute the Python script using the python command:

python digit_check.py

You should see the following output:

The string '12345' is valid.

Now, let's modify the input_string to "1234a" and run the script again:

## ~/project/digit_check.py
input_string = "1234a"
expected_length = 5

## Check if the string contains only digits and has the expected length
if len(input_string) == expected_length and input_string.isdigit():
    print(f"The string '{input_string}' is valid.")
else:
    print(f"The string '{input_string}' is invalid.")
python digit_check.py

You should see the following output:

The string '1234a' is invalid.

Finally, let's modify the input_string to "123456" and run the script again:

## ~/project/digit_check.py
input_string = "123456"
expected_length = 5

## Check if the string contains only digits and has the expected length
if len(input_string) == expected_length and input_string.isdigit():
    print(f"The string '{input_string}' is valid.")
else:
    print(f"The string '{input_string}' is invalid.")
python digit_check.py

You should see the following output:

The string '123456' is invalid.

This demonstrates how you can combine the isdigit() method and length validation to create more robust input validation logic.

Summary

In this lab, you learned how to identify digit characters in Python using the isdigit() method. You created a digit_check.py file, assigned a character to a variable, and used isdigit() to determine if it was a digit. The script then printed a message indicating whether the character was a digit or not.

You tested the script with both a digit character ('5') and a non-digit character ('A'), observing the different outputs based on the isdigit() method's return value. This demonstrated the basic usage of isdigit() for character validation.