-4

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.

6
  • It's just a random keyboard smash to illustrate. Commented Mar 4, 2023 at 18:44
  • 2
    The code that "works as intended" would raise a ValueError Commented Mar 4, 2023 at 18:45
  • A hexadecimal number includes the characters 0-9 and a-f. Not all of a-z. Commented Mar 4, 2023 at 18:45
  • 3
    Please don't smash, because your first code does not work as intended. Commented Mar 4, 2023 at 18:45
  • 1
    Could you clarify what you mean by "turn an alphanumeric string into a hexadecimal number"? Are you just trying to turn an arbitrary alphanumeric string into some arbitrary number? Commented Mar 4, 2023 at 18:46

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.