Reputation: 507
Where can I find a complete tutorial or documentation on os.urandom
? I need to get get a random int to choose a char from a string of 80 characters.
Upvotes: 13
Views: 29164
Reputation: 4857
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/
Upvotes: 8
Reputation: 12174
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()
.
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
Upvotes: 23