Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

random alphanumeric string into hexadecimal in Python

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks for the help, extremely new to Python.

>Solution :

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 for 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading