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

其他回答

这个方法比Ignacio发布的random.choice()方法稍快,也稍令人讨厌。

它利用了伪随机算法的特性,按位和移位的存储体比为每个字符生成新的随机数更快。

# must be length 32 -- 5 bits -- the question didn't specify using the full set
# of uppercase letters ;)
_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'

def generate_with_randbits(size=32):
    def chop(x):
        while x:
            yield x & 31
            x = x >> 5
    return  ''.join(_ALPHABET[x] for x in chop(random.getrandbits(size * 5))).ljust(size, 'A')

…创建一个生成器,该生成器每次从0..31取出5位数字,直到没有剩余

…join()生成器对随机数的结果与正确的位

使用Timeit,对于32个字符串,计时为:

[('generate_with_random_choice', 28.92901611328125),
 ('generate_with_randbits', 20.0293550491333)]

…但对于64个字符串,randbits会丢失;)

除非我真的不喜欢我的同事,否则我可能永远不会在生产代码中使用这种方法。

edit:更新以适应问题(仅限大写和数字),并使用按位运算符&和>>而不是%和//

如果需要随机字符串而不是伪随机字符串,则应使用os.urandom作为源

from os import urandom
from itertools import islice, imap, repeat
import string

def rand_string(length=5):
    chars = set(string.ascii_uppercase + string.digits)
    char_gen = (c for c in imap(urandom, repeat(1)) if c in chars)
    return ''.join(islice(char_gen, None, length))

基于另一个Stack Overflow答案,创建随机字符串和随机十六进制数的最轻量级方法,比公认答案更好的版本是:

('%06x' % random.randrange(16**6)).upper()

更快。

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

from chancepy import Chance

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

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