在Python中生成特定长度的随机字符串的最佳方法是什么?

Bra*_*don 37 python random

对于一个项目,我需要一种创建数千个随机字符串同时保持低冲突的方法.我正在寻找他们只有12个字符长和大写.有什么建议?

Pet*_*aro 98

码:

from random import choice
from string import ascii_uppercase

print(''.join(choice(ascii_uppercase) for i in range(12)))
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

5个例子:

QPUPZVVHUNSN
EFJACZEBYQEB
QBQJJEEOYTZY
EOJUSUEAJEEK
QWRWLIWDTDBD
Run Code Online (Sandbox Code Playgroud)

编辑:

如果你只需要数字,使用digits,而不是不断ascii_uppercase从一个string模块.

3个例子:

229945986931
867348810313
618228923380
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是误导:*"12位长和大写"* - 因为数字不能大写 (4认同)

Omi*_*aha 16

通过Django,您可以get_random_stringdjango.utils.crypto模块中使用功能.

get_random_string(length=12,
    allowed_chars=u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
Run Code Online (Sandbox Code Playgroud)

例:

get_random_string()
u'ngccjtxvvmr9'

get_random_string(4, allowed_chars='bqDE56')
u'DDD6'
Run Code Online (Sandbox Code Playgroud)

但如果你不想拥有Django,这里是它的独立代码:

码:

import random
import hashlib
import time

SECRET_KEY = 'PUT A RANDOM KEY WITH 50 CHARACTERS LENGTH HERE !!'

try:
    random = random.SystemRandom()
    using_sysrandom = True
except NotImplementedError:
    import warnings
    warnings.warn('A secure pseudo-random number generator is not available '
                  'on your system. Falling back to Mersenne Twister.')
    using_sysrandom = False


def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
Run Code Online (Sandbox Code Playgroud)