问题:具有大写字母和数字的随机字符串生成
我想生成一个大小为N的字符串。
它应该由数字和大写英文字母组成,例如:
我如何以pythonic方式实现这一目标?
I want to generate a string of size N.
It should be made up of numbers and uppercase English letters such as:
How can I achieve this in a pythonic way?
回答 0
一行回答:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
甚至更短,从Python 3.6开始,使用random.choices()
:
''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
加密更安全的版本;参见https://stackoverflow.com/a/23728630/2213647:
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
详细而言,具有清除函数以进一步重用:
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
它是如何工作的 ?
我们导入string
,一个包含常见ASCII字符序列的模块,以及random
一个处理随机生成的模块。
string.ascii_uppercase + string.digits
只是串联表示大写ASCII字符和数字的字符列表:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
然后,我们使用列表推导创建“ n”个元素的列表:
>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']
在上面的例子中,我们使用[
创建列表,但我们不这样做的id_generator
功能,所以Python没有在内存中创建列表,但生成的飞行元素,一个接一个(更多相关信息点击这里)。
而不是要求创建字符串的n倍elem
,我们将要求Python创建从字符序列中选取的随机字符的n倍:
>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'
因此,random.choice(chars) for _ in range(size)
实际上是在创建一个size
字符序列。从chars
以下位置随机选择的字符:
>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']
然后,我们将它们与一个空字符串连接起来,以便序列成为一个字符串:
>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
Answer in one line:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
or even shorter starting with Python 3.6 using random.choices()
:
''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
A cryptographically more secure version; see https://stackoverflow.com/a/23728630/2213647:
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
In details, with a clean function for further reuse:
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
How does it work ?
We import string
, a module that contains sequences of common ASCII characters, and random
, a module that deals with random generation.
string.ascii_uppercase + string.digits
just concatenates the list of characters representing uppercase ASCII chars and digits:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
Then we use a list comprehension to create a list of ‘n’ elements:
>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']
In the example above, we use [
to create the list, but we don’t in the id_generator
function so Python doesn’t create the list in memory, but generates the elements on the fly, one by one (more about this here).
Instead of asking to create ‘n’ times the string elem
, we will ask Python to create ‘n’ times a random character, picked from a sequence of characters:
>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'
Therefore random.choice(chars) for _ in range(size)
really is creating a sequence of size
characters. Characters that are randomly picked from chars
:
>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']
Then we just join them with an empty string so the sequence becomes a string:
>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
回答 1
该堆栈溢出问题是“随机字符串Python”在Google上当前排名最高的结果。当前的最佳答案是:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
这是一种极好的方法,但是随机PRNG并不是加密安全的。我假设许多研究此问题的人都希望生成用于加密或密码的随机字符串。您可以通过在上面的代码中进行一些小的更改来安全地执行此操作:
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
使用random.SystemRandom()
的,而不是在* nix机器只是随机使用/ dev / urandom的,并CryptGenRandom()
在Windows中。这些是加密安全的PRNG。在需要安全PRNG的应用程序中使用random.choice
代替random.SystemRandom().choice
可能会造成灾难性的后果,并且鉴于这个问题的普遍性,我敢打赌,这个错误已经犯了很多遍了。
如果您使用的是python3.6或更高版本,则可以使用MSeifert的答案中提到的新的secrets模块:
''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
该模块文档还讨论了生成安全令牌和最佳实践的便捷方法。
This Stack Overflow quesion is the current top Google result for “random string Python”. The current top answer is:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
This is an excellent method, but the PRNG in random is not cryptographically secure. I assume many people researching this question will want to generate random strings for encryption or passwords. You can do this securely by making a small change in the above code:
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
Using random.SystemRandom()
instead of just random uses /dev/urandom on *nix machines and CryptGenRandom()
in Windows. These are cryptographically secure PRNGs. Using random.choice
instead of random.SystemRandom().choice
in an application that requires a secure PRNG could be potentially devastating, and given the popularity of this question, I bet that mistake has been made many times already.
If you’re using python3.6 or above, you can use the new secrets module as mentioned in MSeifert’s answer:
''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
The module docs also discuss convenient ways to generate secure tokens and best practices.
回答 2
只需使用Python的内置uuid:
如果您可以使用UUID,请使用内置的uuid软件包。
一线解决方案:
import uuid; uuid.uuid4().hex.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
Simply use Python’s builtin uuid:
If UUIDs are okay for your purposes, use the built-in uuid package.
One Line Solution:
import uuid; uuid.uuid4().hex.upper()[0:6]
In Depth Version:
Example:
import uuid
uuid.uuid4() #uuid4 => full random uuid
# Outputs something like: UUID('0172fc9a-1dac-4414-b88d-6b9a6feb91ea')
If you need exactly your format (for example, “6U1S75”), you can do it like this:
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
回答 3
一种更简单,更快速但稍微少一点的随机方式是使用random.sample
而不是分别选择每个字母,如果允许n次重复,则将您的随机基础扩大n倍,例如
import random
import string
char_set = string.ascii_uppercase + string.digits
print ''.join(random.sample(char_set*6, 6))
注意:random.sample防止字符重用,乘以字符集的大小可以进行多次重复,但是与纯随机选择相比,它们的可能性仍然较小。如果我们选择长度为6的字符串,并选择“ X”作为第一个字符,则在选择示例中,第二个字符获得“ X”的几率与获得“ X”作为第二个字符的几率相同第一个字符。在random.sample实现中,将“ X”作为任何后续字符的几率仅为将其作为第一个字符的机会的6/7
A simpler, faster but slightly less random way is to use random.sample
instead of choosing each letter separately, If n-repetitions are allowed, enlarge your random basis by n times e.g.
import random
import string
char_set = string.ascii_uppercase + string.digits
print ''.join(random.sample(char_set*6, 6))
Note: random.sample prevents character reuse, multiplying the size of the character set makes multiple repetitions possible, but they are still less likely then they are in a pure random choice. If we go for a string of length 6, and we pick ‘X’ as the first character, in the choice example, the odds of getting ‘X’ for the second character are the same as the odds of getting ‘X’ as the first character. In the random.sample implementation, the odds of getting ‘X’ as any subsequent character are only 6/7 the chance of getting it as the first character
回答 4
import uuid
lowercase_str = uuid.uuid4().hex
lowercase_str
是一个像 'cea8b32e00934aaea8c005a35d85a5c0'
uppercase_str = lowercase_str.upper()
uppercase_str
是 'CEA8B32E00934AAEA8C005A35D85A5C0'
import uuid
lowercase_str = uuid.uuid4().hex
lowercase_str
is a random value like 'cea8b32e00934aaea8c005a35d85a5c0'
uppercase_str = lowercase_str.upper()
uppercase_str
is 'CEA8B32E00934AAEA8C005A35D85A5C0'
回答 5
执行此操作的更快,更轻松,更灵活的方法是使用模块(pip install StringGenerator
)。
生成一个包含大写字母和数字的6个字符的随机字符串:
>>> from strgen import StringGenerator as SG
>>> SG("[\u\d]{6}").render()
u'YZI2CI'
获取唯一列表:
>>> SG("[\l\d]{10}").render_list(5,unique=True)
[u'xqqtmi1pOk', u'zmkWdUr63O', u'PGaGcPHrX2', u'6RZiUbkk2i', u'j9eIeeWgEF']
保证一个“特殊”字符字符串:
>>> SG("[\l\d]{10}&[\p]").render()
u'jaYI0bcPG*0'
随机的HTML颜色:
>>> SG("#[\h]{6}").render()
u'#CEdFCa'
等等
我们需要意识到:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
可能没有数字(或大写字符)。
strgen
比上述任何一种解决方案的开发时间都更快。Ignacio提供的解决方案是运行速度最快的解决方案,并且是使用Python标准库的正确答案。但是您几乎不会以这种形式使用它。您将要使用SystemRandom(如果不可用,则使用备用版本),确保表示所需的字符集,使用(或不使用unicode),确保连续的调用产生唯一的字符串,使用字符串模块字符类之一的子集,等等。这比提供的答案需要更多的代码。概括解决方案的各种尝试都具有局限性,strgen使用简单的模板语言可以以更高的简洁性和更高的表达力来解决。
在PyPI上:
pip install StringGenerator
披露:我是strgen模块的作者。
A faster, easier and more flexible way to do this is to use the module (pip install StringGenerator
).
Generate a 6-character random string with upper case letters and digits:
>>> from strgen import StringGenerator as SG
>>> SG("[\u\d]{6}").render()
u'YZI2CI'
Get a unique list:
>>> SG("[\l\d]{10}").render_list(5,unique=True)
[u'xqqtmi1pOk', u'zmkWdUr63O', u'PGaGcPHrX2', u'6RZiUbkk2i', u'j9eIeeWgEF']
Guarantee one “special” character in the string:
>>> SG("[\l\d]{10}&[\p]").render()
u'jaYI0bcPG*0'
A random HTML color:
>>> SG("#[\h]{6}").render()
u'#CEdFCa'
etc.
We need to be aware that this:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
might not have a digit (or uppercase character) in it.
strgen
is faster in developer-time than any of the above solutions. The solution from Ignacio is the fastest run-time performing and is the right answer using the Python Standard Library. But you will hardly ever use it in that form. You will want to use SystemRandom (or fallback if not available), make sure required character sets are represented, use unicode (or not), make sure successive invocations produce a unique string, use a subset of one of the string module character classes, etc. This all requires lots more code than in the answers provided. The various attempts to generalize a solution all have limitations that strgen solves with greater brevity and expressive power using a simple template language.
It’s on PyPI:
pip install StringGenerator
Disclosure: I’m the author of the strgen module.
回答 6
从Python 3.6开始,如果需要加密的secrets
模块,则应使用模块而不是模块(否则,此答案与@Ignacio Vazquez-Abrams的答案相同):random
from secrets import choice
import string
''.join([choice(string.ascii_uppercase + string.digits) for _ in range(N)])
还有一点需要注意:列表理解str.join
比使用生成器表达式要快!
From Python 3.6 on you should use the secrets
module if you need it to be cryptographically secure instead of the random
module (otherwise this answer is identical to the one of @Ignacio Vazquez-Abrams):
from secrets import choice
import string
''.join([choice(string.ascii_uppercase + string.digits) for _ in range(N)])
One additional note: a list-comprehension is faster in the case of str.join
than using a generator expression!
回答 7
回答 8
如果您需要一个随机字符串而不是伪随机字符串,则应使用它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))
If you need a random string rather than a pseudo random one, you should use os.urandom
as the source
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))
回答 9
我以为还没有人回答这个大声笑!但是,嘿,这是我自己做的:
import random
def random_alphanumeric(limit):
#ascii alphabet of all alphanumerals
r = (range(48, 58) + range(65, 91) + range(97, 123))
random.shuffle(r)
return reduce(lambda i, s: i + chr(s), r[:random.randint(0, len(r))], "")
I thought no one had answered this yet lol! But hey, here’s my own go at it:
import random
def random_alphanumeric(limit):
#ascii alphabet of all alphanumerals
r = (range(48, 58) + range(65, 91) + range(97, 123))
random.shuffle(r)
return reduce(lambda i, s: i + chr(s), r[:random.randint(0, len(r))], "")
回答 10
与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个字符串,randbit会失败;)
除非我真的不喜欢我的同事,否则我可能永远不会在生产代码中使用这种方法。
编辑:已更新为适合该问题(仅适用于大写和数字),并使用按位运算符&和>>代替%和//
This method is slightly faster, and slightly more annoying, than the random.choice() method Ignacio posted.
It takes advantage of the nature of pseudo-random algorithms, and banks on bitwise and and shift being faster than generating a new random number for each character.
# 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')
…create a generator that takes out 5 bit numbers at a time 0..31 until none left
…join() the results of the generator on a random number with the right bits
With Timeit, for 32-character strings, the timing was:
[('generate_with_random_choice', 28.92901611328125),
('generate_with_randbits', 20.0293550491333)]
…but for 64 character strings, randbits loses out ;)
I would probably never use this approach in production code unless I really disliked my co-workers.
edit: updated to suit the question (uppercase and digits only), and use bitwise operators & and >> instead of % and //
回答 11
我会这样:
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) )
I’d do it this way:
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
Or just:
def rand_string(length, char_set=legals):
return ''.join( random.choice(char_set) for _ in range(length) )
回答 12
回答 13
有时0(零)和O(字母O)可能会造成混淆。所以我用
import uuid
uuid.uuid4().hex[:6].upper().replace('0','X').replace('O','Y')
Sometimes 0 (zero) & O (letter O) can be confusing. So I use
import uuid
uuid.uuid4().hex[:6].upper().replace('0','X').replace('O','Y')
回答 14
>>> 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 string
>>> import random
the following logic still generates 6 character random sample
>>> print ''.join(random.sample((string.ascii_uppercase+string.digits),6))
JT7K3Q
No need to multiply by 6
>>> print ''.join(random.sample((string.ascii_uppercase+string.digits)*6,6))
TK82HK
回答 15
对于那些喜欢使用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))))
它首先通过从给定池中生成一个随机选择的符号的不确定序列,然后将该序列分解为多个长度部分,然后再进行连接,然后生成一个连接的随机序列的不确定的[infinite]迭代器,它应与支持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)
如果您不想使用下一代,则可以使其可调用:
>>> 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
该连接,我们只需调用即可提取下一个完全生成的块,当然,这个示例似乎有点麻烦,而且它是…
For those of you who enjoy functional 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))))
It generates an indefinite [infinite] iterator, of joined random sequences, by first generating an indefinite sequence of randomly selected symbol from the giving pool, then breaking this sequence into length parts which is then joined, it should work with any sequence that supports getitem, by default it simply generates a random sequence of alpha numeric letters, though you can easily modify to generate other things:
for example to generate random tuples of digits:
>>> 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)
if you don’t want to use next for generation you can simply make it callable:
>>> irand_tuples = irand_seqs(xrange(10), join=tuple)
>>> make_rand_tuples = partial(next, irand_tuples)
>>> make_rand_tuples()
(1, 6, 2, 8, 1, 9)
if you want to generate the sequence on the fly simply set join to identity.
>>> irand_tuples = irand_seqs(xrange(10), join=identity)
>>> selections = next(irand_tuples)
>>> next(selections)
8
>>> list(selections)
[6, 3, 8, 2, 2]
As others have mentioned if you need more security then set the appropriate select function:
>>> from random import SystemRandom
>>> rand_strs = irand_seqs(select=SystemRandom().choice)
'QsaDxQ'
the default selector is choice
which may select the same symbol multiple times for each chunk, if instead you’d want the same member selected at most once for each chunk then, one possible usage:
>>> 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]
we use sample
as our selector, to do the complete selection, so the chunks are actually length 1, and to join we simply call next
which fetches the next completely generated chunk, granted this example seems a bit cumbersome and it is …
回答 16
(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
(1) This will give you all caps and numbers:
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) If you later want to include lowercase letters in your key, then this will also work:
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
回答 17
这是对Anurag Uniyal的回应,也是我自己的工作。
import random
import string
oneFile = open('Numbers.txt', 'w')
userInput = 0
key_count = 0
value_count = 0
chars = string.ascii_uppercase + string.digits + string.punctuation
for userInput in range(int(input('How many 12 digit keys do you want?'))):
while key_count <= userInput:
key_count += 1
number = random.randint(1, 999)
key = number
text = str(key) + ": " + str(''.join(random.sample(chars*6, 12)))
oneFile.write(text + "\n")
oneFile.close()
this is a take on Anurag Uniyal ‘s response and something that i was working on myself.
import random
import string
oneFile = open('Numbers.txt', 'w')
userInput = 0
key_count = 0
value_count = 0
chars = string.ascii_uppercase + string.digits + string.punctuation
for userInput in range(int(input('How many 12 digit keys do you want?'))):
while key_count <= userInput:
key_count += 1
number = random.randint(1, 999)
key = number
text = str(key) + ": " + str(''.join(random.sample(chars*6, 12)))
oneFile.write(text + "\n")
oneFile.close()
回答 18
>>> import random
>>> str = []
>>> chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
>>> num = int(raw_input('How long do you want the string to be? '))
How long do you want the string to be? 10
>>> for k in range(1, num+1):
... str.append(random.choice(chars))
...
>>> str = "".join(str)
>>> str
'tm2JUQ04CK'
该random.choice
函数从列表中选择一个随机条目。您还创建了一个列表,以便可以将字符追加到for
语句中。在端str是[ ‘T’, ‘M’, ‘2’, ‘J’, ‘U’, ‘Q’, ‘0’, ‘4’, ‘C’, ‘K’],但str = "".join(str)
需要照顾您,留下您'tm2JUQ04CK'
。
希望这可以帮助!
>>> import random
>>> str = []
>>> chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
>>> num = int(raw_input('How long do you want the string to be? '))
How long do you want the string to be? 10
>>> for k in range(1, num+1):
... str.append(random.choice(chars))
...
>>> str = "".join(str)
>>> str
'tm2JUQ04CK'
The random.choice
function picks a random entry in a list. You also create a list so that you can append the character in the for
statement. At the end str is [‘t’, ‘m’, ‘2’, ‘J’, ‘U’, ‘Q’, ‘0’, ‘4’, ‘C’, ‘K’], but the str = "".join(str)
takes care of that, leaving you with 'tm2JUQ04CK'
.
Hope this helps!
回答 19
import string
from random import *
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(8, 16)))
print password
import string
from random import *
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(8, 16)))
print password
回答 20
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="")
在这里,可以在for循环中更改字符串的长度,即在range(1,length)中的i可以更改。这是一种简单易懂的算法。它使用列表,因此您可以丢弃不需要的字符。
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="")
Here length of string can be changed in for loop i.e for i in range(1,length) It is simple algorithm which is easy to understand. it uses list so you can discard characters that you do not need.
回答 21
一个简单的:
import string
import random
character = string.lowercase + string.uppercase + string.digits + string.punctuation
char_len = len(character)
# you can specify your password length here
pass_len = random.randint(10,20)
password = ''
for x in range(pass_len):
password = password + character[random.randint(0,char_len-1)]
print password
A simple one:
import string
import random
character = string.lowercase + string.uppercase + string.digits + string.punctuation
char_len = len(character)
# you can specify your password length here
pass_len = random.randint(10,20)
password = ''
for x in range(pass_len):
password = password + character[random.randint(0,char_len-1)]
print password
回答 22
我想建议您下一个选择:
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]
I would like to suggest you next option:
import crypt
n = 10
crypt.crypt("any sring").replace('/', '').replace('.', '').upper()[-n:-1]
Paranoic mode:
import uuid
import crypt
n = 10
crypt.crypt(str(uuid.uuid4())).replace('/', '').replace('.', '').upper()[-n:-1]
回答 23
两种方法:
import random, math
def randStr_1(chars:str, length:int) -> str:
chars *= math.ceil(length / len(chars))
chars = letters[0:length]
chars = list(chars)
random.shuffle(characters)
return ''.join(chars)
def randStr_2(chars:str, length:int) -> str:
return ''.join(random.choice(chars) for i in range(chars))
基准测试:
from timeit import timeit
setup = """
import os, subprocess, time, string, random, math
def randStr_1(letters:str, length:int) -> str:
letters *= math.ceil(length / len(letters))
letters = letters[0:length]
letters = list(letters)
random.shuffle(letters)
return ''.join(letters)
def randStr_2(letters:str, length:int) -> str:
return ''.join(random.choice(letters) for i in range(length))
"""
print('Method 1 vs Method 2', ', run 10 times each.')
for length in [100,1000,10000,50000,100000,500000,1000000]:
print(length, 'characters:')
eff1 = timeit("randStr_1(string.ascii_letters, {})".format(length), setup=setup, number=10)
eff2 = timeit("randStr_2(string.ascii_letters, {})".format(length), setup=setup, number=10)
print('\t{}s : {}s'.format(round(eff1, 6), round(eff2, 6)))
print('\tratio = {} : {}\n'.format(eff1/eff1, round(eff2/eff1, 2)))
输出:
Method 1 vs Method 2 , run 10 times each.
100 characters:
0.001411s : 0.00179s
ratio = 1.0 : 1.27
1000 characters:
0.013857s : 0.017603s
ratio = 1.0 : 1.27
10000 characters:
0.13426s : 0.151169s
ratio = 1.0 : 1.13
50000 characters:
0.709403s : 0.855136s
ratio = 1.0 : 1.21
100000 characters:
1.360735s : 1.674584s
ratio = 1.0 : 1.23
500000 characters:
6.754923s : 7.160508s
ratio = 1.0 : 1.06
1000000 characters:
11.232965s : 14.223914s
ratio = 1.0 : 1.27
第一种方法的性能更好。
Two methods :
import random, math
def randStr_1(chars:str, length:int) -> str:
chars *= math.ceil(length / len(chars))
chars = letters[0:length]
chars = list(chars)
random.shuffle(characters)
return ''.join(chars)
def randStr_2(chars:str, length:int) -> str:
return ''.join(random.choice(chars) for i in range(chars))
Benchmark :
from timeit import timeit
setup = """
import os, subprocess, time, string, random, math
def randStr_1(letters:str, length:int) -> str:
letters *= math.ceil(length / len(letters))
letters = letters[0:length]
letters = list(letters)
random.shuffle(letters)
return ''.join(letters)
def randStr_2(letters:str, length:int) -> str:
return ''.join(random.choice(letters) for i in range(length))
"""
print('Method 1 vs Method 2', ', run 10 times each.')
for length in [100,1000,10000,50000,100000,500000,1000000]:
print(length, 'characters:')
eff1 = timeit("randStr_1(string.ascii_letters, {})".format(length), setup=setup, number=10)
eff2 = timeit("randStr_2(string.ascii_letters, {})".format(length), setup=setup, number=10)
print('\t{}s : {}s'.format(round(eff1, 6), round(eff2, 6)))
print('\tratio = {} : {}\n'.format(eff1/eff1, round(eff2/eff1, 2)))
Output :
Method 1 vs Method 2 , run 10 times each.
100 characters:
0.001411s : 0.00179s
ratio = 1.0 : 1.27
1000 characters:
0.013857s : 0.017603s
ratio = 1.0 : 1.27
10000 characters:
0.13426s : 0.151169s
ratio = 1.0 : 1.13
50000 characters:
0.709403s : 0.855136s
ratio = 1.0 : 1.21
100000 characters:
1.360735s : 1.674584s
ratio = 1.0 : 1.23
500000 characters:
6.754923s : 7.160508s
ratio = 1.0 : 1.06
1000000 characters:
11.232965s : 14.223914s
ratio = 1.0 : 1.27
The performance of first method is better.
回答 24
我已经回答了几乎所有答案,但是看起来都没有那么容易。我建议您尝试使用passgen库,该库通常用于创建随机密码。
您可以生成随机字符串,长度,标点,数字,字母和大小写。
这是您的情况的代码:
from passgen import passgen
string_length = int(input())
random_string = passgen(length=string_length, punctuation=False, digits=True, letters=True, case='upper')
I have gone though almost all of the answers but none of them looks easier. I would suggest you to try the passgen library which is generally used to create random passwords.
You can generate random strings of your choice of length, punctuation, digits, letters and case.
Here’s the code for your case:
from passgen import passgen
string_length = int(input())
random_string = passgen(length=string_length, punctuation=False, digits=True, letters=True, case='upper')
回答 25
生成随机的16字节ID包含字母,数字,“ _”和“-”
os.urandom(16).translate((f'{string.ascii_letters}{string.digits}-_'*4).encode('ascii'))
Generate random 16-byte ID containig letters, digits, ‘_’ and ‘-‘
os.urandom(16).translate((f'{string.ascii_letters}{string.digits}-_'*4).encode('ascii'))
回答 26
import string, random
lower = string.ascii_lowercase
upper = string.ascii_uppercase
digits = string.digits
special = '!"£$%^&*.,@#/?'
def rand_pass(l=4, u=4, d=4, s=4):
p = []
[p.append(random.choice(lower)) for x in range(l)]
[p.append(random.choice(upper)) for x in range(u)]
[p.append(random.choice(digits)) for x in range(d)]
[p.append(random.choice(special)) for x in range(s)]
random.shuffle(p)
return "".join(p)
print(rand_pass())
# @5U,@A4yIZvnp%51
import string, random
lower = string.ascii_lowercase
upper = string.ascii_uppercase
digits = string.digits
special = '!"£$%^&*.,@#/?'
def rand_pass(l=4, u=4, d=4, s=4):
p = []
[p.append(random.choice(lower)) for x in range(l)]
[p.append(random.choice(upper)) for x in range(u)]
[p.append(random.choice(digits)) for x in range(d)]
[p.append(random.choice(special)) for x in range(s)]
random.shuffle(p)
return "".join(p)
print(rand_pass())
# @5U,@A4yIZvnp%51
回答 27
我发现这更简单,更清洁。
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以仅执行alpha字母数字或仅数字或奇怪字符或任何您想要的操作。
I found this to be simpler and cleaner.
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
Just change the 64 to vary the length, vary the CharacterPool to do alpha only alpha numeric or numeric only or strange characters or whatever you want.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。