在Python的眾多函數中,能夠十分方便地操作字符串的函數,小編認為就有必要提及到strip()和replace()了。
strip() 方法
概念:用於移除字符串頭尾指定的字符(默認為空格)。
strip()語法:str.strip([chars]);
參數:chars,即對應需要操作的字符串
返回值:移除字符串頭尾指定的字符生成的新字符串。
舉個例子:
代碼演示:
str1 = "0000000 infonan 0000000" print(str1.strip( '0' )) # 去除首尾字符 0 str2 = " infonan " # 去除首尾空格 print(str2.strip())
輸出結果:
infonan
infonan
trip()函數的其他用法:
- str.strip(str_rm) 刪除str字符串中開頭、結尾處,位於str_rm刪除序列的字符
- str.lstrip(str_rm) 刪除str字符串中開頭處,位於str_rm刪除序列的字符
- str.rstrip(str_rm) 刪除str字符串中結尾處,位於str_rm刪除序列的字符
注意 :
① 當str_rm為空的情況時,默認刪除空白符(包括'\n', '\r', '\t', ' ')
代碼演示:
a = ' 123' print(a.strip()) b='\t\tabc' print(b) c = 'sdff\r\n' print(c.strip())
輸出結果:
'123' 'abc' 'sdff'
② str_rm刪除序列是隻要首尾的字符在刪除序列內,就會被刪除掉。
代碼演示:
a = '123abc' print(a.strip('21')) print(a.strip('12'))
輸出結果:
'3abc' '3abc'
replace()方法
概念:replace() 方法把字符串中的 舊字符(old) 替換成 新字符串(new) ,如果指定第三個參數max,則代表替換次數不超過 max 次。
語法:str.replace(old, new[, max])
參數:
old —— 將被替換的子字符串。
new —— 新字符串,用於替換old子字符串。
max —— 可選字符串, 替換不超過 max 次
返回值:返回字符串中的 舊字符串(old) 替換成 新字符串(new) 後生成的新字符串,如果指定第三個參數max,則替換不超過 max 次。
栗子:
代碼演示:
str = "This is info" print ("小編 舊 筆名:", str) print ("小編 新 筆名:", str.replace("info", "InfoNan")) str = "this is a old string example for replace" print (str.replace("old", "new", 2))
輸出結果:
小編 舊 筆名:This is info 小編 新 筆名:This is InfoNan this is a new string example for replace
需要學習Python的朋友可以私信小編,私信回覆“資料”,即可免費領取小編整理的一套Python零基礎入門資料。