python学习笔记之字符串(str),,字符宽度和精度:>>


字符宽度和精度:>>>frommathimportpi>>>‘%10f‘%pi#字段宽10‘3.141593‘>>>‘%10.2f‘%pi#字段宽10,精度2‘3.14‘>>>‘%.2f‘%pi#精度2‘3.14‘>>>‘%.5s‘%‘GuidovanRossum‘#指定获取字符串的个数‘Guido‘>>>‘%-10.2f‘%pi#左对齐‘3.14‘>>>‘%+10.2f‘%pi#右对齐‘+3.14‘find方法:返回字符串所在位置的最左端索引>>>data=‘Withamoo-moohere,andamoo-moothere‘>>>data.find(‘moo‘)7join方法:将给定的字符串按照指定的链接符号拼接在一起>>>dirs=[‘usr‘,‘bin‘,‘env‘]>>>‘/‘.join(dirs)‘usr/bin/envlower方法:将大写字母转换为小写字母>>>user=‘TrondheimHammerDance‘>>>user.lower()‘trondheimhammerdance‘title方法:将字符串转换为标题>>>"that‘sallfloks".title()"That‘SAllFloks"replace方法:替换指定的字符串,替换多个字符>>>data=‘Thisisatest‘>>>data.replace(‘is‘,‘Jeff‘)‘ThJeffJeffatestsplit方法:按照指定的分隔符,分割字符串>>>dirs=‘/usr/sbin/env‘>>>dirs.split(‘/‘)[‘‘,‘usr‘,‘sbin‘,‘env‘]strip方法:去除两侧(不包括内部)空格的字符串>>>‘whywhatwhowhenhow‘.strip()‘whywhatwhowhenhow‘translate方法:与replace方法一样,只替换单个字符>>>fromstringimportmaketrans>>>table=maketrans(‘cs‘,‘kz‘)>>>table[97:123]‘abkdefghijklmnopqrztuvwxyz‘>>>maketrans(‘‘,‘‘)[97:123]‘abcdefghijklmnopqrstuvwxyz‘>>>‘thisisanincredibletest‘.translate(table)‘thizizaninkredibletezt‘>>>‘thisisanincredibletest‘.translate(table,‘‘)#第二个参数为要删除的字符‘thizizaninkredibletezt‘


本文出自 “马行空” 博客,谢绝转载!

python学习笔记之字符串(str)

评论关闭