本文主要總結字符串的知識點。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