在 Python 中生成特定长度的随机字符串的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18319101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to generate random strings of a specific length in Python?
提问by Brandon
For a project, I need a method of creating thousands of random strings while keeping collisions low. I'm looking for them to be only 12 characters long and uppercase only. Any suggestions?
对于一个项目,我需要一种创建数千个随机字符串同时保持低冲突的方法。我正在寻找它们只有 12 个字符长和大写。有什么建议?
采纳答案by Peter Varo
CODE:
代码:
from random import choice
from string import ascii_uppercase
print(''.join(choice(ascii_uppercase) for i in range(12)))
OUTPUT:
输出:
5 examples:
5个例子:
QPUPZVVHUNSN
EFJACZEBYQEB
QBQJJEEOYTZY
EOJUSUEAJEEK
QWRWLIWDTDBD
EDIT:
编辑:
If you need only digits, use the digits
constant instead of the ascii_uppercase
one from the string
module.
如果你只需要数字,使用digits
恒定的,而不是ascii_uppercase
从一个string
模块。
3 examples:
3个例子:
229945986931
867348810313
618228923380
回答by Jon Clements
Could make a generator:
可以做一个发电机:
from string import ascii_uppercase
import random
from itertools import islice
def random_chars(size, chars=ascii_uppercase):
selection = iter(lambda: random.choice(chars), object())
while True:
yield ''.join(islice(selection, size))
random_gen = random_chars(12)
print next(random_gen)
# LEQIITOSJZOQ
print next(random_gen)
# PXUYJTOTHWPJ
Then just pull from the generator when they're needed... Either using next(random_gen)
when you need them, or use random_200 = list(islice(random_gen, 200))
for instance...
然后只需在需要时从发电机中拉出...要么next(random_gen)
在需要时使用它们,要么使用random_200 = list(islice(random_gen, 200))
例如...
回答by Sylvain Leroux
For cryptographically strong pseudo-random bytes you might use the pyOpenSSLwrapper around OpenSSL.
对于加密强的伪随机字节,您可以使用围绕 OpenSSL的pyOpenSSL包装器。
It provides the bytes
function to gather a pseudo-random sequences of bytes.
它提供了bytes
收集伪随机字节序列的功能。
from OpenSSL import rand
b = rand.bytes(7)
BTW, 12 uppercase letters is a little bit more that 56 bits of entropy. You will only to have to read 7 bytes.
顺便说一句,12 个大写字母比 56 位熵多一点。您只需读取 7 个字节。
回答by Omid Raha
By Django
, you can use get_random_string
function in django.utils.crypto
module.
通过Django
,您可以get_random_string
在django.utils.crypto
模块中使用函数。
get_random_string(length=12,
allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
Example:
例子:
get_random_string()
u'ngccjtxvvmr9'
get_random_string(4, allowed_chars='bqDE56')
u'DDD6'
But if you don't want to have Django
, hereis independent code of it:
但是如果你不想有Django
,这里是它的独立代码:
Code:
代码:
import random
import hashlib
import time
SECRET_KEY = 'PUT A RANDOM KEY WITH 50 CHARACTERS LENGTH HERE !!'
try:
random = random.SystemRandom()
using_sysrandom = True
except NotImplementedError:
import warnings
warnings.warn('A secure pseudo-random number generator is not available '
'on your system. Falling back to Mersenne Twister.')
using_sysrandom = False
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
回答by Manoj Selvin
This function generates random string of UPPERCASE letters with the specified length,
此函数生成指定长度的大写字母随机字符串,
eg:length = 6, will generate the following random sequence pattern
eg:length = 6,会生成如下随机序列模式
YLNYVQ
YLNYVQ
import random as r
def generate_random_string(length):
random_string = ''
random_str_seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(0,length):
if i % length == 0 and i != 0:
random_string += '-'
random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
return random_string
回答by u991073
#!/bin/python3
import random
import string
def f(n: int) -> str:
bytes(random.choices(string.ascii_uppercase.encode('ascii'),k=n)).decode('ascii')
run faster for very big n. avoid str concatenate.
对于非常大的 n 运行得更快。避免 str 连接。