What is the hexdigits constant in Python?

The string module in Python

The string module in Python is a collection of different constants.

The hexdigits constant

The hexdigits constant in the string module contains all the ASCII hexadecimal digits.

The constant’s value is as follows:

0123456789abcdefABCDEF

Syntax

string.hexdigits

As hexdigits is a constant, we can access it via the string module name.

Example 1

Let’s have a look at the code below:

import string
hexdigits_output = string.hexdigits
print("string.hexdigits = '%s'" % (hexdigits_output))

Explanation

  • Line 1: We import the string module.
  • Line 3: We store the output of string.hexdigits in the hexdigits_output variable.
  • Line 5: We print hexdigits_output.

Example 2

Let’s have a look at the code below:

import string
def is_hexdigits_only(str_input):
for i in str_input:
if i not in string.hexdigits:
return False
return True
str_to_check_1 = "aba123fdf"
print("Does %s contains only hexadecimal digits? %s" % (str_to_check_1, is_hexdigits_only(str_to_check_1)))
str_to_check_2 = "abji232daosfdgfRFDFD"
print("Does %s contains only hexadecimal digits? %s" % (str_to_check_2, is_hexdigits_only(str_to_check_2)))

Explanation

  • Line 1: We import the string module.
  • Lines 3–9: We define a method called is_hexdigits_only that accepts a string as the parameter. It also checks whether or not the input string contains only ASCII hexadecimal digits.
  • Line 11: We define a string called str_to_check_1 that contains only ASCII hexadecimal digits.
  • Line 12: We invoke the is_hexdigits_only method, and pass str_to_check_1 as a parameter.
  • Line 14: We define a string called str_to_check_2 that contains lowercase and uppercase ASCII letters and digits.
  • Line 15: We invoke the is_hexdigits_only method, and pass str_to_check_2 as a parameter.

Free Resources