string
moduleThe string
module in Python is a collection of different constants.
digits
constantThe 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
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.
import stringdigits_output = string.digitsprint("string.digits = '%s'" % (digits_output))
Line 1: We import the string
module.
Line 3: We store the output of string.digits
in the variable called digits_output
.
Line 5: We print the variable digits_output
.
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)))
Line 1: We import the string
module.
Lines 3–9: We define a function called contains_digits
that 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_1
that contains only ASCII letters.
Line 12: We invoke the contains_digits
function by passing str_to_check_1
as a parameter.
Line 14: We define a string called str_to_check_2
that contains digits and ASCII letters.
Line 15: We invoke the contains_digits
function by passing str_to_check_2
as a parameter.