参考链接: Python字符串| ascii_letters
Python3基础:String模块ascii_letters和digits
(其实不止是python3 可以, python2.7 也可以)
本文介绍Python3中String模块ascii_letters和digits方法,其中ascii_letters是生成所有字母,从a-z和A-Z,digits是生成所有数字0-9.
示例如下:
Python
>>> chars = string.ascii_letters string.digits
>>> print(chars)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
1
2
3
>>>
chars
=
string
.
ascii_letters
string
.
digits
>>>
(
chars
)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
生成所有字母和数字干什么?在哪个场景中会用到呢,举个例子:比如生成激活码(优惠券),激活码一般都是字母和数字组成的,首先要有一个所有字母和数字的字符串,然后随机取出几个字母或数字。
Python
import random, string
def rand_str(num, length=7):
f = open('Activation_code.txt', 'w')
for i in range(num):
chars = string.ascii_letters string.digits
s = [random.choice(chars) for i in range(length)]
f.write('{0}n'.format(''.join(s)))
f.close()
if __name__ == '__main__':
rand_str(200)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import
random
,
string
def
rand_str
(
num
,
length
=
7
)
:
f
=
open
(
'Activation_code.txt'
,
'w'
)
for
i
in
range
(
num
)
:
chars
=
string
.
ascii_letters
string
.
digits
s
=
[
random
.
choice
(
chars
)
for
i
in
range
(
length
)
]
f
.
write
(
'{0}n'
.
format
(
''
.
join
(
s
)
)
)
f
.
close
(
)
if
__name__
==
'__main__'
:
rand_str
(
200
)
执行结果片段:
wz0dajI 25vlulV zLHkx9Y GGzu0Ip RilbYKW 4WZL2IC 4syobYw kCMky7O oUPde55 KrMRmUX Ct0W2Pm wMwpPdk ydPuy9h Z7vo3r9 emcmQl0 GeIDKw3 PK9BLvg z4xNdVb I0EGA9O YPUh5UA 69gISVt Xun7GI3 YufPaD0 DsYZx2Q 3JfW1bh ydHELg6 NxNMRBa (最后一段代码示例来自https://github.com/tanteng/python/blob/master/DIYgod/0001/random_string.py,经过修正以运行在Python3下)