How do you check if a string contains only decimal characters in Python?
Posted by QuinnLw
Last Updated: August 20, 2024
In Python, checking if a string contains only decimal characters can be efficiently accomplished using the str.isdecimal() method. This method returns True if all characters in the string are decimal characters and there is at least one character. It returns False otherwise. Here's a simple overview of how to use this method:
Using str.isdecimal()
The isdecimal() method checks the string against Unicode character properties. Decimal characters include digits 0-9 and other characters that represent decimal numbers in various locales.
Example:
# Example string
string1 = "12345"
string2 = "123abc"

# Checking if the strings are decimal
is_decimal1 = string1.isdecimal()
is_decimal2 = string2.isdecimal()

print(f"Is '{string1}' a decimal string? {is_decimal1}")  # Output: True
print(f"Is '{string2}' a decimal string? {is_decimal2}")  # Output: False
Alternative: Regular Expressions
In situations where additional control over the string validation is needed (such as allowing optional whitespace or leading zeroes), using regular expressions might be appropriate. The re module can be used for this purpose.
import re

# Regular expression for checking decimal digits
def is_decimal_string(s):
    return bool(re.fullmatch(r'\d+', s))

# Test examples
print(is_decimal_string("12345"))  # Output: True
print(is_decimal_string("123abc"))  # Output: False
Summary
To determine if a string contains only decimal characters in Python, the str.isdecimal() method provides a straightforward solution for most scenarios. For more complex requirements, regular expressions can offer the flexibility needed.