字符宽度和精度: >>> from math import pi >>> ‘%10f‘%pi #字段宽10 ‘ 3.141593‘ >>> ‘%10.2f‘ %pi #字段宽10,精度2 ‘ 3.14‘ >>> ‘%.2f‘%pi #精度2 ‘3.14‘ >>> ‘%.5s‘ %‘Guido van Rossum‘ #指定获取字符串的个数 ‘Guido‘ >>> ‘%-10.2f‘ %pi #左对齐 ‘3.14 ‘ >>> ‘%+10.2f‘ %pi #右对齐 ‘ +3.14‘ find方法:返回字符串所在位置的最左端索引 >>> data = ‘With a moo-moo here, and a moo-moo there‘ >>> data.find(‘moo‘) 7 join方法:将给定的字符串按照指定的链接符号拼接在一起 >>> dirs = [‘usr‘,‘bin‘,‘env‘] >>> ‘/‘.join(dirs) ‘usr/bin/env lower方法:将大写字母转换为小写字母 >>> user = ‘Trondheim Hammer Dance‘ >>> user.lower() ‘trondheim hammer dance‘ title方法:将字符串转换为标题 >>> "that‘s all floks".title() "That‘S All Floks" replace方法:替换指定的字符串,替换多个字符 >>> data = ‘This is a test‘ >>> data.replace(‘is‘,‘Jeff‘) ‘ThJeff Jeff a test split方法:按照指定的分隔符,分割字符串 >>> dirs = ‘/usr/sbin/env‘ >>> dirs.split(‘/‘) [‘‘, ‘usr‘, ‘sbin‘, ‘env‘] strip方法:去除两侧(不包括内部)空格的字符串 >>> ‘ why what who when how ‘.strip() ‘why what who when how‘ translate方法:与replace方法一样,只替换单个字符 >>> from string import maketrans >>> table = maketrans(‘cs‘,‘kz‘) >>> table[97:123] ‘abkdefghijklmnopqrztuvwxyz‘ >>> maketrans(‘‘,‘‘)[97:123] ‘abcdefghijklmnopqrstuvwxyz‘ >>> ‘this is an incredible test‘.translate(table) ‘thiz iz an inkredible tezt‘ >>> ‘this is an incredible test‘.translate(table, ‘ ‘)#第二个参数为要删除的字符 ‘thizizaninkredibletezt‘
本文出自 “马行空” 博客,谢绝转载!
原文地址:http://maxingkong.blog.51cto.com/6184921/1897602