如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
当前回答
我想建议您下一个选择:
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]
其他回答
使用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
>>> import string
>>> import random
以下逻辑仍然生成6个字符的随机样本
>>> print ''.join(random.sample((string.ascii_uppercase+string.digits),6))
JT7K3Q
无需乘以6
>>> print ''.join(random.sample((string.ascii_uppercase+string.digits)*6,6))
TK82HK
我会这样做:
import random
from string import digits, ascii_uppercase
legals = digits + ascii_uppercase
def rand_string(length, char_set=legals):
output = ''
for _ in range(length): output += random.choice(char_set)
return output
或者只是:
def rand_string(length, char_set=legals):
return ''.join( random.choice(char_set) for _ in range(length) )
我想建议您下一个选择:
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的内置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