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

6个754z4英国U911K4型


当前回答

一种无重复的随机生成器函数,使用一个集合来存储以前生成的值。注意,如果字符串或数量非常大,这将消耗一些内存,而且可能会稍微慢一点。发电机将在给定量或达到最大可能组合时停止。

代码:

#!/usr/bin/env python

from typing import Generator
from random import SystemRandom as RND
from string import ascii_uppercase, digits


def string_generator(size: int = 1, amount: int = 1) -> Generator[str, None, None]:
    """
    Return x random strings of a fixed length.

    :param size: string length, defaults to 1
    :type size: int, optional
    :param amount: amount of random strings to generate, defaults to 1
    :type amount: int, optional
    :yield: Yield composed random string if unique
    :rtype: Generator[str, None, None]
    """
    CHARS = list(ascii_uppercase + digits)
    LIMIT = len(CHARS) ** size
    count, check, string = 0, set(), ''
    while LIMIT > count < amount:
        string = ''.join(RND().choices(CHARS, k=size))
        if string not in check:
            check.add(string)
            yield string
            count += 1


for my_count, my_string in enumerate(string_generator(6, 20)):
    print(my_count, my_string)

输出:

0 RS9N3P
1 S0GDGR
2 ZNBLFV
3 96FF97
4 38JJZ3
5 Q3214A
6 VLWNK1
7 QMT05E
8 X1ZFP0
9 MZF442
10 10L9AZ
11 GE8HIQ
12 S7PA43
13 MVLXO9
14 YX7Y0G
15 GIIKPF
16 3KCUQA
17 XHIXFV
18 BJQ5VG
19 HQF01Q

如果字符串始终需要包含字母和数字,请使用以下命令:

#!/usr/bin/env python

from typing import Generator
from random import SystemRandom as RND
from string import ascii_uppercase, digits


def string_generator(size: int = 2, amount: int = 1) -> Generator[str, None, None]:
    """
    Return x random strings of a fixed length.

    :param size: string length, defaults to 1
    :type size: int, optional
    :param amount: amount of random strings to generate, defaults to 1
    :type amount: int, optional
    :yield: Yield composed random string if unique
    :rtype: Generator[str, None, None]
    """
    if size < 2:
        print(
            'Since the string must contain letters and numbers,',
            'its size must be at least two characters',
        )
        return
    CHARS = list(ascii_uppercase + digits)
    LIMIT = len(CHARS) ** size
    count, check, string = 0, set(), ''
    while LIMIT > count < amount:
        while 1:
            string = ''.join(RND().choices(CHARS, k=size))
            if not (string.isalpha() or string.isnumeric()):
                break
        if string not in check:
            check.add(string)
            yield string
            count += 1


for my_count, my_string in enumerate(string_generator(6, 20)):
    print(my_count, my_string)

输出:

0 5JIITL
1 3W7AI1
2 8QMO10
3 ETHAI8
4 BLFPP9
5 50X2CC
6 1LI8WA
7 39CKET
8 R4IM0E
9 Q3KHGS
10 65CBIU
11 XTRHO4
12 N2XIGO
13 06VFCW
14 VE9MJ8
15 A9ADHK
16 Y5ROJ0
17 OH7EJF
18 TQ709S
19 P0DDNJ

其他回答

到目前为止,没有一个答案能保证存在某些类别的字符,如大写、小写、数字等;因此,其他答案可能会导致密码没有数字等。奇怪的是,这样的功能不是标准库的一部分。以下是我使用的:

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)

我在寻找不同的答案,并花时间阅读了秘密文件

机密模块用于生成适合于管理数据(如密码、帐户验证、安全令牌和相关机密)的加密强随机数。特别是,应优先使用秘密,而不是随机模块中的默认伪随机数生成器,其设计用于建模和模拟,而不是安全或密码学。

深入了解它所提供的功能,我发现如果你想模仿像Google Drive ID这样的ID,我会发现一个非常方便的功能:

secrets.token_urlsafe([nbytes=无])返回随机URL安全文本字符串,包含n字节随机字节。文本是Base64编码的,因此平均每个字节大约有1.3个字符。如果nbytes为None或未提供,则使用合理的默认值。

使用方法如下:

import secrets
import math

def id_generator():
    id = secrets.token_urlsafe(math.floor(32 / 1.3))
    return id

print(id_generator())

输出32个字符的长度id:

joXR8dYbBDAHpVs5ci6iD-oIgPhkeQFk

我知道这与OP的问题稍有不同,但我希望这对许多正在寻找与我相同用例的人仍然有帮助。

我以为还没有人回答这个问题,哈哈!但嘿,这是我自己的尝试:

import random

def random_alphanumeric(limit):
    #ascii alphabet of all alphanumerals
    r = (range(48, 58) + range(65, 91) + range(97, 123))
    random.shuffle(r)
    return reduce(lambda i, s: i + chr(s), r[:random.randint(0, len(r))], "")

一种更简单、更快但随机性稍低的方法是使用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

一种无重复的随机生成器函数,使用一个集合来存储以前生成的值。注意,如果字符串或数量非常大,这将消耗一些内存,而且可能会稍微慢一点。发电机将在给定量或达到最大可能组合时停止。

代码:

#!/usr/bin/env python

from typing import Generator
from random import SystemRandom as RND
from string import ascii_uppercase, digits


def string_generator(size: int = 1, amount: int = 1) -> Generator[str, None, None]:
    """
    Return x random strings of a fixed length.

    :param size: string length, defaults to 1
    :type size: int, optional
    :param amount: amount of random strings to generate, defaults to 1
    :type amount: int, optional
    :yield: Yield composed random string if unique
    :rtype: Generator[str, None, None]
    """
    CHARS = list(ascii_uppercase + digits)
    LIMIT = len(CHARS) ** size
    count, check, string = 0, set(), ''
    while LIMIT > count < amount:
        string = ''.join(RND().choices(CHARS, k=size))
        if string not in check:
            check.add(string)
            yield string
            count += 1


for my_count, my_string in enumerate(string_generator(6, 20)):
    print(my_count, my_string)

输出:

0 RS9N3P
1 S0GDGR
2 ZNBLFV
3 96FF97
4 38JJZ3
5 Q3214A
6 VLWNK1
7 QMT05E
8 X1ZFP0
9 MZF442
10 10L9AZ
11 GE8HIQ
12 S7PA43
13 MVLXO9
14 YX7Y0G
15 GIIKPF
16 3KCUQA
17 XHIXFV
18 BJQ5VG
19 HQF01Q

如果字符串始终需要包含字母和数字,请使用以下命令:

#!/usr/bin/env python

from typing import Generator
from random import SystemRandom as RND
from string import ascii_uppercase, digits


def string_generator(size: int = 2, amount: int = 1) -> Generator[str, None, None]:
    """
    Return x random strings of a fixed length.

    :param size: string length, defaults to 1
    :type size: int, optional
    :param amount: amount of random strings to generate, defaults to 1
    :type amount: int, optional
    :yield: Yield composed random string if unique
    :rtype: Generator[str, None, None]
    """
    if size < 2:
        print(
            'Since the string must contain letters and numbers,',
            'its size must be at least two characters',
        )
        return
    CHARS = list(ascii_uppercase + digits)
    LIMIT = len(CHARS) ** size
    count, check, string = 0, set(), ''
    while LIMIT > count < amount:
        while 1:
            string = ''.join(RND().choices(CHARS, k=size))
            if not (string.isalpha() or string.isnumeric()):
                break
        if string not in check:
            check.add(string)
            yield string
            count += 1


for my_count, my_string in enumerate(string_generator(6, 20)):
    print(my_count, my_string)

输出:

0 5JIITL
1 3W7AI1
2 8QMO10
3 ETHAI8
4 BLFPP9
5 50X2CC
6 1LI8WA
7 39CKET
8 R4IM0E
9 Q3KHGS
10 65CBIU
11 XTRHO4
12 N2XIGO
13 06VFCW
14 VE9MJ8
15 A9ADHK
16 Y5ROJ0
17 OH7EJF
18 TQ709S
19 P0DDNJ