如何生成大小为N的字符串,由数字和大写英文字母组成,例如:
6个754z4英国U911K4型
如何生成大小为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以仅使用字母数字、仅使用数字或奇怪的字符或任何您想要的字符。
其他回答
(1) 这将为您提供所有大写和数字:
import string, random
passkey=''
for x in range(8):
if random.choice([1,2]) == 1:
passkey += passkey.join(random.choice(string.ascii_uppercase))
else:
passkey += passkey.join(random.choice(string.digits))
print passkey
(2) 如果您以后想在密钥中包含小写字母,那么这也可以:
import string, random
passkey=''
for x in range(8):
if random.choice([1,2]) == 1:
passkey += passkey.join(random.choice(string.ascii_letters))
else:
passkey += passkey.join(random.choice(string.digits))
print passkey
只需使用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
使用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 random
q=2
o=1
list =[r'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','s','0','1','2','3','4','5','6','7','8','9','0']
while(q>o):
print("")
for i in range(1,128):
x=random.choice(list)
print(x,end="")
这里,字符串的长度可以在循环中改变,即i在范围(1,长度)内这是一个简单的算法,易于理解。它使用列表,所以您可以丢弃不需要的字符。
对于那些喜欢功能python的人:
from itertools import imap, starmap, islice, repeat
from functools import partial
from string import letters, digits, join
from random import choice
join_chars = partial(join, sep='')
identity = lambda o: o
def irand_seqs(symbols=join_chars((letters, digits)), length=6, join=join_chars, select=choice, breakup=islice):
""" Generates an indefinite sequence of joined random symbols each of a specific length
:param symbols: symbols to select,
[defaults to string.letters + string.digits, digits 0 - 9, lower and upper case English letters.]
:param length: the length of each sequence,
[defaults to 6]
:param join: method used to join selected symbol,
[defaults to ''.join generating a string.]
:param select: method used to select a random element from the giving population.
[defaults to random.choice, which selects a single element randomly]
:return: indefinite iterator generating random sequences of giving [:param length]
>>> from tools import irand_seqs
>>> strings = irand_seqs()
>>> a = next(strings)
>>> assert isinstance(a, (str, unicode))
>>> assert len(a) == 6
>>> assert next(strings) != next(strings)
"""
return imap(join, starmap(breakup, repeat((imap(select, repeat(symbols)), None, length))))
它生成一个不定[无限]迭代器,由连接的随机序列组成,首先从给定的池中生成一个随机选择的符号的不定序列,然后将该序列分解为长度部分,然后进行连接,它应该与支持getitem的任何序列一起工作,默认情况下,它只生成一个字母数字字母的随机序列,尽管您可以轻松修改以生成其他内容:
例如生成数字的随机元组:
>>> irand_tuples = irand_seqs(xrange(10), join=tuple)
>>> next(irand_tuples)
(0, 5, 5, 7, 2, 8)
>>> next(irand_tuples)
(3, 2, 2, 0, 3, 1)
如果您不想使用next for generation,您可以简单地将其设置为可调用:
>>> irand_tuples = irand_seqs(xrange(10), join=tuple)
>>> make_rand_tuples = partial(next, irand_tuples)
>>> make_rand_tuples()
(1, 6, 2, 8, 1, 9)
如果您想动态生成序列,只需将join设置为identity即可。
>>> irand_tuples = irand_seqs(xrange(10), join=identity)
>>> selections = next(irand_tuples)
>>> next(selections)
8
>>> list(selections)
[6, 3, 8, 2, 2]
正如其他人所提到的,如果您需要更多的安全性,请设置相应的选择功能:
>>> from random import SystemRandom
>>> rand_strs = irand_seqs(select=SystemRandom().choice)
'QsaDxQ'
默认选择器是choice,它可以为每个块多次选择相同的符号,如果相反,您希望为每个块最多选择一次相同的成员,则有一种可能的用法:
>>> from random import sample
>>> irand_samples = irand_seqs(xrange(10), length=1, join=next, select=lambda pool: sample(pool, 6))
>>> next(irand_samples)
[0, 9, 2, 3, 1, 6]
我们使用sample作为选择器,进行完整的选择,因此块的长度实际上是1,为了加入,我们只需调用next,它获取下一个完全生成的块,当然这个示例看起来有点麻烦,而且它。。。