How do you check if a string contains only digits in Python?
Posted by RoseHrs
Last Updated: August 14, 2024
In Python, checking if a string contains only digits can be accomplished in several ways. The most straightforward method is to use the built-in string method .isdigit(). Here’s a detailed look at how to perform this check along with some alternative methods.
Using the .isdigit() Method
The .isdigit() method checks if all the characters in a string are digits. It returns True if the string consists entirely of digit characters and False otherwise. This method is simple and effective. Example:
string1 = "12345"
string2 = "123a45"

print(string1.isdigit())  # Output: True
print(string2.isdigit())  # Output: False
Using Regular Expressions
For more complex scenarios where additional checks are necessary, such as allowing a specific format (e.g., numbers with leading zeros), the re module can be used. This method is particularly useful if you need to check for digits in a broader context. Example:
import re

def contains_only_digits(s):
    return bool(re.match(r'^\d+$', s))

string1 = "12345"
string2 = "123a45"

print(contains_only_digits(string1))  # Output: True
print(contains_only_digits(string2))  # Output: False
Using str.isnumeric()
The .isnumeric() method is another alternative that checks if all characters in the string are numeric characters. This method goes beyond just checking digits, as it includes other numeric representations, such as fractions and subscripts. Example:
string1 = "12345"
string2 = "2²"  # Superscript 2

print(string1.isnumeric())  # Output: True
print(string2.isnumeric())  # Output: True
Summary
- .isdigit(): Ideal for checking if a string consists solely of digit characters. - Regular Expressions: Useful for more complex patterns or if additional format validations are needed. - .isnumeric(): Similar to .isdigit() but includes other numeric forms. Choosing the right method depends on the specific requirements of the application, such as whether the string needs to strictly contain digits or may also include other numeric formats. Each of these methods provides an efficient way to verify that a string contains only digit characters in Python.