string模块
string模块包括了一些字符串常量, 并且有str对象的功能,主要用来生成一些字符串、字符串格式化等
参考: http://python.usyiyi.cn/python_278/library/string.html
string.ascii_lowercase #生成小写字母a-z字符串 string.ascii_uppercase #生成大写字母A-Z字符串 string.ascii_letters #生成a-z与A-Z字符串组合 string.letters #生成a-z与A-Z字符串组合
>>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' >>> string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.digits '0123456789' >>> string.hexdigits '0123456789abcdefABCDEF' >>> string.letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
字符串格式之format
通过位置对应:
>>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 2.7+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence,解包 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated,参数可以被重复使用 'abracadabra'
通过名称对应,不用考虑顺序
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') 'Coordinates: 37.24N, -115.81W' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) 'Coordinates: 37.24N, -115.81W'
支持*args 、**kwargs
>>> info = dict(name='huangweimin',age=19) >>> info {'age': 19, 'name': 'huangweimin'} >>> >>> 'I am {name},age {age}'.format(**info) 'I am huangweimin,age 19'
// 字符串格式化尽量使用format格式,和函数传参都是一样的,还有很多功能参考官网标准库