如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
当前回答
到目前为止,没有一个答案能保证存在某些类别的字符,如大写、小写、数字等;因此,其他答案可能会导致密码没有数字等。奇怪的是,这样的功能不是标准库的一部分。以下是我使用的:
def random_password(*, nchars = 7, min_nupper = 3, ndigits = 3, nspecial = 3, special=string.punctuation):
letters = random.choices(string.ascii_lowercase, k=nchars)
letters_upper = random.choices(string.ascii_uppercase, k=min_nupper)
digits = random.choices(string.digits, k=ndigits)
specials = random.choices(special, k=nspecial)
password_chars = letters + letters_upper + digits + specials
random.shuffle(password_chars)
return ''.join(password_chars)
其他回答
用一行字回答:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
或者更短,从Python 3.6开始使用random.choices():
''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
加密更安全的版本:请参阅本帖
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
详细地说,具有一个干净的功能,以供进一步重用:
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
它是如何工作的?
我们导入string(一个包含常见ASCII字符序列的模块)和random(一个处理随机生成的模块)。
string.ascii_capital+string.digitals只是连接表示大写ascii字符和数字的字符列表:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
然后,我们使用列表理解创建“n”个元素的列表:
>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']
在上面的示例中,我们使用[来创建列表,但我们没有使用id_generator函数,因此Python不会在内存中创建列表,而是一个接一个地动态生成元素(这里将详细介绍)。
我们不要求创建字符串elem的“n”倍,而是要求Python创建从一系列字符中选取的随机字符“n”次:
>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'
因此,_ in range(size)的随机选择(chars)实际上是在创建一个大小字符序列。从字符中随机选取的字符:
>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']
然后我们用一个空字符串连接它们,这样序列就变成了一个字符串:
>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
这个堆栈溢出问题是当前Google搜索“随机字符串Python”的最高结果。目前最热门的答案是:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
这是一种很好的方法,但随机PRNG在密码上并不安全。我想很多研究这个问题的人都想为加密或密码生成随机字符串。您可以通过对上面的代码进行一个小的更改来安全地执行此操作:
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
使用random.SystemRandom()而不仅仅是random在*nix机器上使用/dev/urandom,在Windows中使用CryptGenRandom(。这些是加密安全的PRNG。在需要安全PRNG的应用程序中使用random.choice而不是random.SystemRandom().choice可能会带来潜在的破坏性,鉴于这个问题的流行性,我敢打赌这个错误已经犯过很多次了。
如果您使用的是python3.6或更高版本,您可以使用MSeiffet回答中提到的新秘密模块:
''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
模块文档还讨论了生成安全令牌的便捷方法和最佳实践。
一种更简单、更快但随机性稍低的方法是使用random.sample,而不是分别选择每个字母。如果允许n次重复,则将随机基础放大n倍。
import random
import string
char_set = string.ascii_uppercase + string.digits
print ''.join(random.sample(char_set*6, 6))
注:random.sample防止字符重复使用,将字符集的大小相乘可以进行多次重复,但它们的可能性仍然小于纯随机选择。如果我们选择长度为6的字符串,并选择“X”作为第一个字符,在选择示例中,第二个字符获得“X”的几率与第一个字符获得的几率相同。在random.sample实现中,将“X”作为任何后续字符的几率只有将其作为第一个字符的几率的6/7
面向安全的方法
我们对任何安全相关的建议都是避免“自己动手”,并使用经过专门安全审查的机密模块。
这来自文档的最佳实践部分:
import string
import secrets
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(8))
由于您特别要求使用大写字母,因此您可以用ascii_capsaper替换ascii_cletters,或者只使用以下内容将密码大写:
password = password.upper()
不以安全为目的的标准方法
这个问题的规范方法(如指定)使用随机模块中的choices()函数:
>>> from random import choices
>>> from string import ascii_uppercase, digits
>>> population = ascii_uppercase + digits
>>> str.join('', choices(population, k=6))
'6JWF1H'
只需使用Python的内置uuid:
如果uuid适合您的用途,请使用内置的uuid包。
单线解决方案:
导入uuid;uuid.uuid4().hhex.upper()[0:6]
深度版本:
例子:
import uuid
uuid.uuid4() #uuid4 => full random uuid
# Outputs something like: UUID('0172fc9a-1dac-4414-b88d-6b9a6feb91ea')
如果您完全需要您的格式(例如,“6U1S75”),可以这样做:
import uuid
def my_random_string(string_length=10):
"""Returns a random string of length string_length."""
random = str(uuid.uuid4()) # Convert UUID format to a Python string.
random = random.upper() # Make all characters uppercase.
random = random.replace("-","") # Remove the UUID '-'.
return random[0:string_length] # Return the random string.
print(my_random_string(6)) # For example, D9E50C