How to Check if a Python String Contains Only Numbers?

In this tutorial, I will explain how to check if a string in Python contains only numbers. As a Python developer, I encountered a scenario where I needed to check if a Python string contained only numbers. I explored more about this topic and I will share my findings in this article.

Methods to Check if a String Contains Only Numbers

Python provides several methods to check if a string contains only numbers. We will explore the most common methods: isdigit(), isnumeric(), and regular expressions.

Read How to Floor a Number in Python?

1. Use isdigit() Method

The isdigit() method is one of the simplest ways to check if a string contains only digits. This method returns True if all characters in the string are digits and there is at least one character, otherwise, it returns False.

Example: Check a Phone Number

Let’s say we have a phone number input, and we want to ensure it contains only digits.

phone_number = "1234567890"

if phone_number.isdigit():
    print("The phone number is valid.")
else:
    print("The phone number is invalid.")

Output:

The phone number is valid.

I have executed the above example code and added the screenshot below.

Check if a Python String Contains Only Numbers

In this example, the isdigit() method will return True because all characters in phone_number are digits.

Check out How to Find Factors of a Number in Python?

2. Use isnumeric() Method

The isnumeric() method is similar to isdigit(), but it also considers other numeric characters such as fractions, subscripts, and superscripts. This method returns True if all characters in the string are numeric.

Example: Checking a ZIP Code

Let’s validate a ZIP code to ensure it contains only numeric characters.

zip_code = "90210"

if zip_code.isnumeric():
    print("The ZIP code is valid.")
else:
    print("The ZIP code is invalid.")

Output:

The ZIP code is valid.

I have executed the above example code and added the screenshot below.

How to Check if a Python String Contains Only Numbers

In this example, isnumeric() will return True because zip_code contains only numeric characters.

Check out How to Format Numbers as Currency in Python?

3. Use Regular Expressions

Regular expressions provide a flexible way to check if a string contains only numbers. The re module in Python allows us to use regular expressions for pattern matching.

Example: Validating a Credit Card Number

Let’s validate a credit card number to ensure it contains only digits.

import re

credit_card_number = "1234567812345678"

if re.fullmatch(r'\d+', credit_card_number):
    print("The credit card number is valid.")
else:
    print("The credit card number is invalid.")

Output:

The credit card number is valid.

I have executed the above example code and added the screenshot below.

Check if a Python String Contains Only Numbers Regular Expressions

In this example, re.fullmatch(r'\d+', credit_card_number) check if credit_card_number contains only digits. The \d+ pattern matches one or more digits.

Read How to Get the Decimal Part of a Number in Python?

Handle Edge Cases

While the methods mentioned above are effective, it’s important to handle edge cases. For instance, you might encounter strings with leading or trailing spaces, or strings that are empty.

Example: Handle Leading and Trailing Spaces

Let’s modify our phone number validation to handle leading and trailing spaces.

phone_number = " 1234567890 "

# Strip leading and trailing spaces
phone_number = phone_number.strip()

if phone_number.isdigit():
    print("The phone number is valid.")
else:
    print("The phone number is invalid.")

In this example, strip() removes any leading or trailing spaces before checking if the string contains only digits.

Read How to Check if a String is a Valid Date in Python?

Example: Handle Empty Strings

Let’s ensure our ZIP code validation handles empty strings.

zip_code = ""

if zip_code.isnumeric() and zip_code:
    print("The ZIP code is valid.")
else:
    print("The ZIP code is invalid.")

In this example, we add a check and zip_code to ensure the string is not empty.

Read How to Convert Month Name to Number in Python?

Conclusion

In this tutorial, I explained how to check if a string in Python contains only numbers. Python provides several methods to achieve this, including isdigit(), isnumeric(), and regular expressions. We also discussed how to handle edge cases.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.