用大写字母和数字生成随机字符串 [英] Random string generation with upper case letters and digits

查看:35
本文介绍了用大写字母和数字生成随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个大小为 N 的字符串.

应该由数字和大写英文字母组成,如:

  • 6U1S75
  • 4Z4UKK
  • U911K4

我怎样才能以 pythonic 方式实现这一点?>

解决方案

一字一句回答:

''.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))

密码学上更安全的版本: 查看这篇文章

''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

在细节上,有一个干净的函数以供进一步重用:

<预><代码>>>>导入字符串>>>随机导入>>>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'>>>字符串.数字'0123456789'>>>string.ascii_uppercase + string.digits'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

然后我们使用列表推导来创建一个包含 'n' 个元素的列表:

<预><代码>>>>range(4) # range 创建一个包含 'n' 个数字的列表[0, 1, 2, 3]>>>['elem' for _ in range(4)] # 我们使用 range 创建 4 次 'elem'['元素','元素','元素','元素']

在上面的例子中,我们使用 [ 来创建列表,但我们没有在 id_generator 函数中,所以 Python 不会在内存中创建列表,但是一个一个地动态生成元素(更多关于这个这里a>).

我们不会要求创建 'n' 次字符串 elem,而是要求 Python 创建 'n' 次随机字符,从字符序列中挑选:

<预><代码>>>>random.choice(abcde")'一种'>>>random.choice(abcde")'d'>>>random.choice(abcde")'乙'

因此 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))'达克'

I want to generate a string of size N.

It should be made up of numbers and uppercase English letters such as:

  • 6U1S75
  • 4Z4UKK
  • U911K4

How can I achieve this in a pythonic way?

解决方案

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 this post

''.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'

这篇关于用大写字母和数字生成随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆