What is digits constant in Python?
The string module
The string module in Python is a collection of different constants.
The digits constant
The digits constant in the string module contains the digits from 0 to 9 in the form of a string.
The value of the constant is as follows:
0123456789
Syntax
string.digits
Since digits is a constant, we can access it via the string module.
Let’s look at two code examples that use the digits constant.
Example 1
import stringdigits_output = string.digitsprint("string.digits = '%s'" % (digits_output))
Explanation
-
Line 1: We import the
stringmodule. -
Line 3: We store the output of
string.digitsin the variable calleddigits_output. -
Line 5: We print the variable
digits_output.
Example 2
import stringdef contains_digit(str_input):for i in str_input:if i in string.digits:return Truereturn Falsestr_to_check_1 = "abjiaosfdgfRFDFD"print("Does %s contain any digits? %s" % (str_to_check_1, contains_digit(str_to_check_1)))str_to_check_2 = "abji232daosfdgfRFDFD"print("Does %s contain any digits? %s" % (str_to_check_2, contains_digit(str_to_check_2)))
Explanation
-
Line 1: We import the
stringmodule. -
Lines 3–9: We define a function called
contains_digitsthat accepts a string as its parameter and checks whether this string has any digits or not. -
Line 11: We define a string called
str_to_check_1that contains only ASCII letters. -
Line 12: We invoke the
contains_digitsfunction by passingstr_to_check_1as a parameter. -
Line 14: We define a string called
str_to_check_2that contains digits and ASCII letters. -
Line 15: We invoke the
contains_digitsfunction by passingstr_to_check_2as a parameter.