经验之谈
小编之前没有用到python的string 模块的一些知识,所以知道的非常局限,最近刷leetcode, 我自己做完题目之后会去看看别人是怎么做的,然后也学习优秀的答题者写代码,自然会有点收获的。
介绍string几个简单的模块知识
- string.ascii_lowercase #### 对应的是26个英文小写字母
- string.ascii_uppercase #### 对应的是26个英文大写字母
- string.digits #### 对应的是10个数字
- string.ascii_letters #### 对应的是 26个英文小写字母和对应的是26个英文大写字母
- string.punctuation #### 对应的是键盘所有英文标点符号
- string.hexdigits #### 对应的十六进制字符
- string.octdigits #### 对应八进制的字符
- string.printable #### 对应的所有键盘出现的符号,同时包括空格之类的符号
- string.whitespace #### 对应的所有的空格符号,但是在pycharm中你打印出来的是乱码,可以在cmd中打印。
直接输出看看都是神马吧
from string import digits
char = digits
print(digits) #### result == 0123456789
from string import ascii_lowercase
str_lower = ascii_lowercase
print(str_lower) #### result == abcdefghijklmnopqrstuvwxyz
from string import ascii_uppercase
str_upper = ascii_uppercase
print(str_upper) #### result == ABCDEFGHIJKLMNOPQRSTUVWXYZ
from string import ascii_letters
res = ascii_letters
print(res) #### result == abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
from string import punctuation
s = punctuation
print(s) ##### result == !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
from string import hexdigits
s = hexdigits
print(s) ##### result == 0123456789abcdefABCDEF
from string import octdigits
s = octdigits
print(s) ##### result == 01234567
from string import printable
s = printable ##### result == 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c
print(s)
from string import whitespace
s = whitespace
print(s) ##### result == \t\n\x0b\x0c\r
运用string的模块
一般而言,这些模块做一些正则匹配、还有生成网站、网页等等的验证码、激活码,我们在填验证信息的时候,手机回传一些验证信息让我们填写,我们同样也可以通过python stirng 模块做到的。
举个一个生成6位数的验证码的例子:
"""
生成验证码:
:type num: int 表示生成的验证码的个数
:type length: int 表示验证码的长度大小
"""
import random
from string import digits
from string import ascii_letters
def random_str(num, length = 6):
f = open("Activation_code.txt", 'w', encoding="utf-8")
for i in range(num):
chars = ascii_letters + digits
s = [random.choice(chars) for i in range(length)]
print("".join(s))
f.write("{0}\n".format("".join(s)))
f.close()
random_str(100, length=6)
结果展示: