Python 3 os.urandom
Might not exactly be on topic, but I want to help those coming here from a search engine. To convert os.urandom
to an integer I'm using this:
import os
rand = int(int(str(os.urandom(4), encoding="UTF-8")).encode('hex'), 16)
# You can then 'cycle' it against the length.
rand_char = chars_list[rand % 80] # or maybe '% len(chars_list)'
Note: The range of the index here is up to that of a 4-byte integer. If you want more, change the 4
to a greater value.
The idea was taken from here: https://pythonadventures.wordpress.com/2013/10/04/generate-a-192-bit-random-number/
If you just need a random integer, you can use random.randint(a, b)
from the random module.
If you need it for crypto purposes, use random.SystemRandom().randint(a, b)
, which makes use of os.urandom()
.
Example
import random
r = random.SystemRandom()
s = "some string"
print(r.choice(s)) # print random character from the string
print(s[r.randrange(len(s))]) # same