本文介绍string模块ascii_letters和digits方法,其中ascii_letters是生成所有字母,从a-z和A-Z,digits是生成所有数字0-9.
示例如下:
In [2]: chars = string.ascii_letters + string.digits In [3]: print(chars) abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
生成所有字母和数字干什么?在哪个场景中会用到呢,举个例子:比如生成激活码(优惠券),激活码一般都是字母和数字组成的,首先要有一个所有字母和数字的字符串,然后随机取出几个字母或数字。
In [3]: import random,string In [4]: 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) ...:
生成了一个Activation_code.txt文件,如图:
内容如下:
NkjmMrL L3Z5BjZ WSTaprg cneoNCQ EtYRNZX gYY14GK hEhhgRM VGD35Vo krtzuHD SLk1D37 68TnbAv RtceKWE cOx7l87 71uT0o6 ClUfT5Q O6nmQWD M2b3sx0 NsCkFKO r6Jh5LM KY57KL0 LpJJweL fHK9ONG SAfZBkc ycmiTla 7IRJHQR 83PhGhP FOKgT8a rHMoCuc sLd1J2C poGo6Hn FuU5H5E pYV3yUq APJSxzl QpFHULN ao63jjZ 4tPi790 cPDTvUQ LMUuKxp m72rvxC C5kvNmk BjeFNig 8ih206i j3RkULM IZnYjqD ILjmKDx K5Z5bQm cBxJziK 8aRpkmU JGqw4mx NSvBFGO mhDGina 6umZHdj 0N2hDyu y6TtW5k sTuII4a hH6CnhT bJRUU9G bK38x7n 7JYKNuO HfZ1R3r fRfvJd5 aMFP1J4 nUFytKX CfoKevR iKvNLiW IvAHqNC dteDej1 GWBvtJL aryuT9G BYFY8t6 S2yCvy4 ZWOYkRy 1bI7ad1 JvMAA86 Nop10tJ XZDetXj idbluDS xyf9M7C TSY2vDZ hBVdw0Z K7bY5Lu vmcI2Kb npy5GJc sYHrBLK mLFYPh1 AnIvBRg TMvzxK0 ObxJ6yP E9eiRh3 EMovni7 1P1jDAb iPEoLuC tfr68fo grNJzjz NNDitm8 Kb7tVWK DhsueP1 5NVMzVR Ekdmfwl Wv2WHui xfh2M0v IKkcdjz 11eMT8M 3Eh2nr3 lHJKpaF P5NEcrn oOdGE06 wVnEsJG aUFEbMU Wryb97U IPoFVDi H2eXNZ5 Ijamrlh 1cMkOTP kLZ5rSj y23jl8O 5Igwd3D t1btfKo 6xoUeaf asOMtG1 24L4VLK jKDeNmH IOg572i pPfynrL tOkZBp1 qeNMVnt fK6Ma2D HI9Bc4i 5S727EW TMi2OBP wbrNLL3 0BxrEIH ADkUpzd EZDqDOP FDLAMtv udfzu28 CPp6Z0G ptf8YNa POt8jpv 4a6fpiK oux3JiK e8fxCw1 z1ZvufB Be6Zl3w WEq7m8W W94B68P qTVfFLC AO9awjc q7AfX9y 4ELYqEW zYAuCeL P9qmKRq 97Py6su hcb62Nr UGZ0mqG 3A71orU P8Q40O8 z3Ia7Xq WQIISLD nwx0xcZ 8HPUXFN eSvJKJE jNG8pyE vMpcPkc v5nkHVl RyNsxSD Fp3SSEC 9bCbLv2 GdMZMYe A8PDaVE DMPvpS5 OWPZFZk GVOAY3j vQefxQK JO415kp Qtbu6rE 0kbPooo F4Lf5Kp mI3Kwt3 qwYybC9 TQJJwlJ ho5k2t4 0Co0A95 wVaggxp TbAKHCD i4bDyx0 EUTAJ5r LiVZv0w yZUoGsD 2LvY0Ie PTXxhpg FQU9dnN TloBN3Z d06uXpk NjlY24X GQjDjUh htcFqlI e8m8bak O6L0QaX U15RVBH