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

6个754z4英国U911K4型


当前回答

这是对Anurak Uniyal的回应的一种理解,也是我自己在研究的东西。

import random
import string

oneFile = open('‪Numbers.txt', 'w')
userInput = 0
key_count = 0
value_count = 0
chars = string.ascii_uppercase + string.digits + string.punctuation

for userInput in range(int(input('How many 12 digit keys do you want?'))):
    while key_count <= userInput:
        key_count += 1
        number = random.randint(1, 999)
        key = number

        text = str(key) + ": " + str(''.join(random.sample(chars*6, 12)))
        oneFile.write(text + "\n")
oneFile.close()

其他回答

>>> import random
>>> str = []
>>> chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
>>> num = int(raw_input('How long do you want the string to be?  '))
How long do you want the string to be?  10
>>> for k in range(1, num+1):
...    str.append(random.choice(chars))
...
>>> str = "".join(str)
>>> str
'tm2JUQ04CK'

random.choice函数在列表中选择一个随机条目。还可以创建一个列表,以便可以在for语句中追加字符。在结尾str是[t','m','2','J','U','Q','0','4','C','K'],但是str=“”.join(str)会处理这一点,留下'tm2JUQ04CK'。

希望这有帮助!

用一行字回答:

''.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'

只需使用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 crypt
n = 10
crypt.crypt("any sring").replace('/', '').replace('.', '').upper()[-n:-1]

妄想模式:

import uuid
import crypt
n = 10
crypt.crypt(str(uuid.uuid4())).replace('/', '').replace('.', '').upper()[-n:-1]

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

from chancepy import Chance

random_string = Chance.string(length=10, pool="someLettersAndNumbers123")