[Python] strip()方法

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(' '))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值