如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
当前回答
有时0(零)和O(字母O)可能会令人困惑。所以我用
import uuid
uuid.uuid4().hex[:6].upper().replace('0','X').replace('O','Y')
其他回答
使用Numpy的随机choice()函数
import numpy as np
import string
if __name__ == '__main__':
length = 16
a = np.random.choice(list(string.ascii_uppercase + string.digits), length)
print(''.join(a))
文档在这里http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.choice.html
这个方法比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:更新以适应问题(仅限大写和数字),并使用按位运算符&和>>而不是%和//
我想建议您下一个选择:
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]
如果需要随机字符串而不是伪随机字符串,则应使用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))
只需使用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