In Python, the string.digits constant contains all the digits from '0' to '9'. This can be very helpful when we need to work with numbers in string form. The string.digit will give the digits '0123456789'.
Let's see how to use strings.digit:
import string
# Using string.digits
dig = string.digits
print(dig)
Output
0123456789
Example 1: Detecting and Extracting Numbers from Mixed String
In many applications, we may need to detect and extract all numbers from a mixed string, such as extracting all the order numbers or item quantities from a report. Using string.digits, we can easily separate numbers from text.
import string
# Mixed string with numbers and text
report = "Order #45: 12 items, Order #46: 7 items"
# Extract all numbers using list comprehension
n = ''.join([ch for ch in report if ch in string.digits])
print(n)
Output
4512467
Example 2: Generating a Random OTP (One-Time Password)
In security applications, generating a one-time password (OTP) is a common task. Using string.digits, we can easily create a secure, random OTP by selecting digits from the string constant.
import string
import random
# Generate a 6-digit OTP
otp = ''.join(random.choices(string.digits, k=6))
print(otp)
Output
262856