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

6个754z4英国U911K4型


当前回答

从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的情况下,列表理解比使用生成器表达式更快!

其他回答

现在可以在这里使用一个新的库(python>=3.6)

from chancepy import Chance

random_string = Chance.string(length=10, pool="someLettersAndNumbers123")
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

一个简单的例子:

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

我已经看过了几乎所有的答案,但没有一个看起来更容易。我建议您尝试密码库,它通常用于创建随机密码。

您可以生成任意长度、标点符号、数字、字母和大小写的字符串。

这是您案例的代码:

from passgen import passgen
string_length = int(input())
random_string = passgen(length=string_length, punctuation=False, digits=True, letters=True, case='upper')

只需使用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