Skip to content
Advertisement

Random 32 hexadecimal digits in Python

I am trying to find a great way to produce a 32 digit hex sequence that is random and gets its randomness from a Big Number like 10*78.

For Python code I also found this:

ran = random.randrange(10**80)
myhex = "%030x" % ran

This produces a 64 digit hex string, BUT sometimes the result is 63 or even 61 characters and I’m not sure why? I need it to return 64 exactly each time.

I need helping tweaking the above code so that it ALWAYS returns 64 only. I do not know enough about the how the “%030x” part works.

I’ve also tried producing a longer hex string and shortening it with:

myhex = myhex[:64]

But I was still seeing strings that were less than 64 being returned.

In the end I just need exactly 64 hexadecimal string derived from a Big Number like 10*78, returned each time.

Solution I went with

import random

ran = random.randrange(10**80)
myhex = "%064x" % ran

#limit string to 64 characters
myhex = myhex[:64]

print(myhex)

Seems @ScottMillers answer below was the key I needed to find the answer so I’m selecting his answer as the solution, but wanted to post my final code that worked for me here.

Thanks everyone

Advertisement

Answer

"%030x" says to display the associated value with at least 30 digits, padding with 0’s in front as necessary. Since your numbers are almost always bigger than that, this isn’t doing much for you.

It sounds like you need "%064x".

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement