strip()函数用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列,并返回删除后的结果
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符
语法
str.strip([chars])
参数
chars :移除字符串头尾指定的字符序列
返回值
返回移除字符串头尾指定的字符生成的新字符串
实例
以下实例展示了strip()函数的使用方法:
str1 = "00000003210Runoob01230000000"
# 去除首尾字符0
print(str1.strip('0')) #3210Runoob0123
str2 = " Runoob "
# 去除首尾空格
print(str2.strip()) #Runoob
# 只要头尾包含有指定字符序列中的字符就删除
str3 = "123abcrunoob321"
# 字符序列为12
print(str3.strip('12')) #3abcrunoob3
txt = ",,,,,rrttgg.....banana....rrr"
x = txt.strip(",.grt")
print(x) #banana
扩展补充
lstrip()函数用于截取掉字符串左边的空格或指定字符,返回截取后的字符串
txt = "_hello_world_"
# hello_world_
print(txt.lstrip('_'))
words = " There are spaces to the left of this sentence."
#There are spaces to the left of this sentence.
print(words.lstrip(' '))
rstrip()函数用于截取掉字符串右边的空格或指定字符,返回截取后的字符串
txt = "_hello_world_"
# _hello_world
print(txt.rstrip('_'))
words = "There are spaces to the right of this sentence. "
#There are spaces to the right of this sentence.
print(words.rstrip(' '))