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