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 string
digits_output = string.digits
print("string.digits = '%s'" % (digits_output))

Explanation

  • 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.

Example 2

import string
def contains_digit(str_input):
for i in str_input:
if i in string.digits:
return True
return False
str_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 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.

Free Resources