描述
Python strip() 方法用于移除字符串頭尾指定的字符(默認為空格)。
語法
strip()方法語法:
str.strip([chars]);
參數
chars -- 移除字符串頭尾指定的字符。
返回值
返回移除字符串頭尾指定的字符生成的新字符串。
實例
以下實例展示了strip()函數的使用方法:
#!/usr/bin/python# -*- coding: UTF-8 -*- str = "0000000 VeVB.COm 0000000"print(str.strip( '0' )) # 去除首尾字符 0 str2 = " VeVB.COm " # 去除首尾空格print(str2.strip())
以上實例輸出結果如下:
VeVB.COm
VeVB.COm
Python3 replace()方法
描述
replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數max,則替換不超過 max 次。
語法
replace()方法語法:
str.replace(old, new[, max])
參數
old -- 將被替換的子字符串。
new -- 新字符串,用于替換old子字符串。
max -- 可選字符串, 替換不超過 max 次
返回值
返回字符串中的 old(舊字符串) 替換成 new(新字符串)后生成的新字符串,如果指定第三個參數max,則替換不超過 max 次。
實例
以下實例展示了replace()函數的使用方法:
#!/usr/bin/python3 str = "歡迎訪問武林網m.survivalescaperooms.com"print ("武林網舊地址:", str)print ("武林網新地址:", str.replace("VeVB.COm", "jbzj.com")) str = "this is string example....wow!!!"print (str.replace("is", "was", 3))以上實例輸出結果如下:
武林網舊地址: www.jbzj.com
武林網新地址: m.survivalescaperooms.com
thwas was string example....wow!!!
函數原型
聲明:s為字符串,rm為要刪除的字符序列
s.strip(rm) 刪除s字符串中開頭、結尾處,位于 rm刪除序列的字符
s.lstrip(rm) 刪除s字符串中開頭處,位于 rm刪除序列的字符
s.rstrip(rm) 刪除s字符串中結尾處,位于 rm刪除序列的字符
注意:
1. 當rm為空時,默認刪除空白符(包括'/n', '/r', '/t', ' ')
例如:
>>> a = ' 123'>>> a.strip()'123'>>> a='/t/tabc''abc'>>> a = 'sdff/r/n'>>> a.strip()'sdff'
2.這里的rm刪除序列是只要邊(開頭或結尾)上的字符在刪除序列內,就刪除掉。
例如 :
>>> a = '123abc'>>> a.strip('21')'3abc' 結果是一樣的>>> a.strip('12')'3abc'文章就到這了,需要的朋友可以參考一下
新聞熱點
疑難解答
圖片精選