描述
Python strip() 方法用于移除字符串頭尾指定的字符(默認(rèn)為空格)或字符序列。
注意:該方法只能刪除開頭或是結(jié)尾的字符,不能刪除中間部分的字符。
語法
strip()方法語法:
str.strip([chars]);
參數(shù)
- chars -- 移除字符串頭尾指定的字符序列。
返回值
返回移除字符串頭尾指定的字符序列生成的新字符串。
實(shí)例
以下實(shí)例展示了 strip() 函數(shù)的使用方法:
實(shí)例(Python 3.0+)
#!/usr/bin/python3
str = "*****this is **string** example....wow!!!*****"
print (str.strip( '*' )) # 指定字符串 *
以上實(shí)例輸出結(jié)果如下:
this is **string** example....wow!!!
從結(jié)果上看,可以注意到中間部分的字符并未刪除。
以下實(shí)例演示了只要頭尾包含有指定字符序列中的字符就刪除:
實(shí)例(Python 3.0+)
#!/usr/bin/python3
str = "123abcrunoob321"
print (str.strip( '12' )) # 字符序列為 12
以上實(shí)例輸出結(jié)果如下:
3abcrunoob3