如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
当前回答
只需使用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
其他回答
面向安全的方法
我们对任何安全相关的建议都是避免“自己动手”,并使用经过专门安全审查的机密模块。
这来自文档的最佳实践部分:
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'
import string
from random import *
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(8, 16)))
print password
到目前为止,没有一个答案能保证存在某些类别的字符,如大写、小写、数字等;因此,其他答案可能会导致密码没有数字等。奇怪的是,这样的功能不是标准库的一部分。以下是我使用的:
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)
我发现这更简单、更干净。
str_Key = ""
str_FullKey = ""
str_CharacterPool = "01234ABCDEFfghij~>()"
for int_I in range(64):
str_Key = random.choice(str_CharacterPool)
str_FullKey = str_FullKey + str_Key
只需更改64以更改长度,更改CharacterPool以仅使用字母数字、仅使用数字或奇怪的字符或任何您想要的字符。
如果需要随机字符串而不是伪随机字符串,则应使用os.urandom作为源
from os import urandom
from itertools import islice, imap, repeat
import string
def rand_string(length=5):
chars = set(string.ascii_uppercase + string.digits)
char_gen = (c for c in imap(urandom, repeat(1)) if c in chars)
return ''.join(islice(char_gen, None, length))