Python strip()方法
描述
Python strip() 方法用於移除字串頭尾指定的字元(默認為空格或換行符)或字元序列。
注意:該方法只能刪除開頭或是結尾的字元,不能刪除中間部分的字元。
語法
strip()方法語法:
str.strip([chars]);
參數
- chars -- 移除字串頭尾指定的字元序列。
返回值
返回移除字串頭尾指定的字元生成的新字串。
實例
以下實例展示了strip()函數的使用方法:
實例(Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = "00000003210zaixian01230000000";
print str.strip( '0' ); # 去除首尾字元 0
str2 = " zaixian "; # 去除首尾空格
print str2.strip();
以上實例輸出結果如下:
3210zaixian0123 zaixian
從結果上看,可以注意到中間部分的字元並未刪除。
以上下例演示了只要頭尾包含有指定字元序列中的字元就刪除:
實例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = "123abczaixian321"
print (str.strip( '12' )) # 字元序列為 12
以上實例輸出結果如下:
3abczaixian3