random alphanumeric string into hexadecimal in Python

Question:

I’m trying to turn an alphanumeric string into a hexadecimal number.

The following code works as intended…

A = "f8g9dsf9s7ff7s9dfg98d9fg97s06s6df5"
B = int(A, 16)

When I try create the alphanumeric dynamically it breaks and doesn’t get converted to hexadecimal number…

A = ''.join(random.choices(string.ascii_lowercase + string.digits, k=34))
B = int(A, 16)

Thanks for the help, extremely new to Python.

Asked By: user1432290

||

Answers:

string.ascii_lowercase is a string composed of the whole alphabet composed from ‘a’ to ‘z’ but only A..F are valid for hexadecimal which is base-16. Calling int() with non-A..F characters will raise a ValueError. Use string "abcdef" for the letters.

import random
import string
A = ''.join(random.choices("abcdef"+ string.digits, k=34))
print(A)
B = int(A, 16)
print(B)

Output:

bf651615fd912a261eb4d5e752aec01f2e
65128298786024663864994496613621589614382
Answered By: CodeMonkey
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.