描述
Python strip() 方法用於移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。
注意:該方法只能刪除開頭或是結尾的字符,不能刪除中間部分的字符。
語法
strip()方法語法:
str.strip([chars]);
參數
- chars -- 移除字符串頭尾指定的字符序列。
返回值
返回移除字符串頭尾指定的字符生成的新字符串。
實例
以下實例展示了strip()函數的使用方法:
# !/usr/bin/python
# -*- coding: UTF-8 -*-
str = "00000003210Runoob01230000000";
str.strip('0'); # 去除首尾字符 0
str2 = " Runoob "; # 去除首尾空格
str2.strip();
輸出結果
3210Runoob0123
Runoob
實例2去除左邊空白和右邊空白
def test_A():
a=' 2 '
b=a.lstrip()
print(b)
c=a.rstrip()
print(c)
if __name__ == '__main__':
test_A()
輸出結果