Open In App

Python string – hexdigits

Last Updated : 05 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, string.hexdigits is a pre-initialized string used as a string constant. It is a collection of valid hexadecimal characters, which include digits (0-9) and letters (A-F and a-f).

Let’s understand how to use string. hexdigits.

Python
# import string library 
import string 

res = string.hexdigits  
print(res) 

Output
0123456789abcdefABCDEF

Explanation:

  • string.hexdigits: This retrieves all valid characters for hexadecimal numbers (0-9) and both lowercase and uppercase letters (a-f).

Syntax of hexdigits

string.hexdigits

Parameters:

  • This doesn’t take any parameter, since it’s not a function.

Returns:

  • This return all hexadecimal digit letters.

How to validate hexadecimal strings?

To validate a hexadecimal string, we check if all the characters are either numbers (0-9) or letters (a-f, A-F). If any character is different, the string isn’t valid.

Python
import string

s1 = "0123456789abcdef"
res= all(char in string.hexdigits for char in s1)

print(res)

Output
True

Explanation:

  • char in string.hexdigits: For each character in s1, this condition checks if it’s a valid hexadecimal character.
  • all(): This function returns True if all characters meet the condition, and False if any character doesn’t meet it.

Generate random password

To generate a random password, we pick characters randomly from numbers (0-9) and letters (a-f, A-F) to create a secure password.

Python
import random
import string

# length of password
a=7
p= ''.join(random.choice(string.hexdigits) for i in range(a))
print(p)

Output
a75c1c2

Explanation:

  • random.choice(string.hexdigits): This picks a random character from the set of numbers and letters .
  • for i in range(a): This repeats the process of picking a random character a times .
  • “”.join():Random characters are combined into a password.


Next Article
Article Tags :
Practice Tags :

Similar Reads