如何生成大小为N的字符串,由数字和大写英文字母组成,例如:

6个754z4英国U911K4型


当前回答

我发现这更简单、更干净。

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以仅使用字母数字、仅使用数字或奇怪的字符或任何您想要的字符。

其他回答

我发现这更简单、更干净。

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以仅使用字母数字、仅使用数字或奇怪的字符或任何您想要的字符。

我会这样做:

import random
from string import digits, ascii_uppercase

legals = digits + ascii_uppercase

def rand_string(length, char_set=legals):

    output = ''
    for _ in range(length): output += random.choice(char_set)
    return output

或者只是:

def rand_string(length, char_set=legals):

    return ''.join( random.choice(char_set) for _ in range(length) )

一个简单的例子:

import string
import random
character = string.lowercase + string.uppercase + string.digits + string.punctuation
char_len = len(character)
# you can specify your password length here
pass_len = random.randint(10,20)
password = ''
for x in range(pass_len):
    password = password + character[random.randint(0,char_len-1)]
print password

从Python 3.6开始,如果你需要密码安全,你应该使用secrets模块,而不是随机模块(否则这个答案与@Ignacio Vazquez Abrams的答案相同):

from secrets import choice
import string

''.join([choice(string.ascii_uppercase + string.digits) for _ in range(N)])

还有一点需要注意:在str.join的情况下,列表理解比使用生成器表达式更快!

有时0(零)和O(字母O)可能会令人困惑。所以我用

import uuid
uuid.uuid4().hex[:6].upper().replace('0','X').replace('O','Y')