Joh*_*ohn 9 python random python-3.x
我在哪里可以找到os.urandom上的完整教程或文档?我需要得到一个随机的int来从一个80字符串的字符串中选择一个字符
我在aser aspire 5920上运行Ubuntu 12.04
Tim*_*Tim 17
如果您只需要一个随机整数,则可以使用random.randint(a, b)随机模块.
如果您需要它用于加密目的,请使用random.SystemRandom().randint(a, b),使用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
Run Code Online (Sandbox Code Playgroud)
可能不完全是主题,但我想帮助那些来自搜索引擎的人.要转换os.urandom为整数我正在使用此:
import os
rand = int(os.urandom(4).encode('hex'), 16)
# You can then 'cycle' it against the length.
rand_char = chars_list[rand % 80] # or maybe '% len(chars_list)'
Run Code Online (Sandbox Code Playgroud)
注意:此处的索引范围最大为4字节整数的范围.如果您想要更多,请将4其更改为更大的值.
这个想法来自这里:https://pythonadventures.wordpress.com/2013/10/04/generate-a-192-bit-random-number/