本文主要总结字符串的知识点。this
1、字符串格式化spa
字符串格式化使用百分号%来实现。rest
#字符串格式化一个值 hellosta = "hello,%s" str = "susan" print(hellosta % str) #hello,susan hellotwo = "hello,%s and %s" names = ("su","jane") names2 = ["su","jame"] #只有元组和字典能够格式化一个以上的值 print(hellotwo % names) #hello,su and jane print(hellotwo % names2) #TypeError: not enough arguments for format string
#%后面加上字典的键(用圆括号括起来),后面再跟上其余说明元素
dictnum = {'one':123,'two':234}
dictstr = "hello,%(two)s"%dictnum
print(dictstr) #hello,234code
基本的转换说明符包括如下部分:orm
(1)%字符:标记转换说明符的开始。blog
(2)转换标志(可选):- 表示左对齐;+ 表示在转换值以前要加上正负号;“”(空白字符)表示正数以前保留空格;0表示转换值若位数不够则用0填充。索引
(3)最小字段宽度(可选):转换后的字符串至少应该具备该值指定的宽度。若是是*,则宽度从值元组中读出;ip
(4)点(.)后跟精度值(可选):若是转换的是实数,精度值就表示出如今小数点后的位数。若是转换的是字符串,那么该数字就表示最大字段宽度。若是是*,那么精度将会从元组中读出。字符串
(5)转换类型:string
例子:
#精度为2 p = '%.2f'%pi print(p) #3.14 #宽度为5 p2 = '%.5s'%'hello,world' print(p2) #hello #也能够用*表示精度和宽度 p3 = '%.*s'%(5,'hello,world') print(p3) #hello
也可使用模板字符串格式化--这个能够查看(Python 自动生成代码 方法二 )这篇文章。
2、字符串方法
一、查找子串
find方法能够在一个较长的字符串中查找子串,它返回子串所在位置的最左端索引,若是没有找到则返回-1.
str = "hello,world.It started" substr = 'world' print(str.find(substr)) #6 nostr = 'su' print(str.find(nostr)) #-1
二、大小写
str1 = "Hello,World.That`s All" str2 = "hello,world.that`s all" #小写 print(str1.lower()) #hello,world.that`s all #大写 print(str2.upper()) #HELLO,WORLD.THAT`S ALL #单词首字母大写,有点瑕疵 print(str2.title()) #Hello,World.That`S All print(string.capwords(str2)) #Hello,world.that`s All
三、替换字符\字符串
replace方法返回某字符串的全部匹配项均被替换以后获得字符串。
translate方法能够替换字符串中的某些部分,和replace方法不一样的是,它只处理单个字符。
restr = "this is a cat.cat is lovely" #restr.replace(old, new, count),count表示最多能够替换多少个字符串 print(restr.replace('cat', 'dog', 1)) #this is a dog.cat is lovely #translate(table) table = str.maketrans('it','ad') print(restr.translate(table)) #dhas as a cad.cad as lovely
四、链接\分割\除空格
join方法用来链接序列中的元素;
split方法用来将字符串分割成序列;
strip方法返回去除两侧(不包括内部)空格的字符串;
seq = ['a','2','c','d'] sep = '+' joinstr = sep.join(seq) print(joinstr) #a+2+c+d splitstr = joinstr.split('+') print(splitstr) #['a', '2', 'c', 'd'] stripstr = " !!hello world !! ** " print(stripstr.strip()) #!!hello world !! ** print(stripstr.strip(' *!')) #hello world