string.hexdigits in Python

In this tutorial, we will learn about hexdigits and string.hexdigits in Python. We will also see an example code to show the use of string.hexdigits in Python.

What is string.hexdigits in Python

In simple words, it is a string of hexadecimal digits, i.e, it is a combination of digits 0-9 and characters, A-F and a-f.

Syntax: string.hexdigits

Also, note that it is not a function therefore there will be no parameters taken.

Since string.hexdigits in Python is an operation of string, therefore, string module needs to be imported as :

import string

print(string.hexdigits)

The output of the following line of code will give the pre-initialized string constant as output :

0123456789abcdefABCDEF


Code: string.hexdigits

Let’s write the code for creating random strong passwords using Python.

import random

import string

a = []  # an empty array created
length = int(input("Number of character in Password"))
for _ in range(length):
    a.append(random.choice(string.hexdigits))
b = ''.join(map(str, a))  # to remove gaps and joining elements of array a
print("The Generated Password is " + b)
  • If you are not able to understand the logic of  join, you can also use :
print("The Generated Password is", end=" ")
for _ in a:
    print(_, end="")

Input-

Number of character in Password

9

Output-

The Generated Password is E1D8375AA

Explanation

  • Importing the module random and module string to use their respective operations.
  • Then we ask the user to enter the length of the password they need.
  • Use string.hexdigits to generate a hexadecimal string.
  • The function random.choice() to choose any character from the string generated by string.hexdigits operation,
  • We use the join() to concatenate the elements of the array and convert them to a string using the map function.

You can also read about: Python Program to Compute Euclidean Distance

Leave a Reply

Your email address will not be published. Required fields are marked *