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