Python rstrip函数踩坑记录

问题背景

从许多中文的参考文献上,rstrip() 函数的功能被简单描述为 :删除字符串末尾的指定字符(默认为空格),我的理解是,直接去掉末尾指定的字符序列,如我传入的是d,则会去掉末尾的字符d(如果存在),如果传入了字符ad,则去掉末尾的字符ad(如果存在),直到我们开发的服务遇到了一个非常奇怪的bug之后,下面是奇怪问题的复现过程:

>>> s = 'hello_world'
>>> s.rstrip('d') # 去除末尾的字符d
'hello_worl'
>>> 
>>> s.rstrip('ld') # 去除末尾的字符 ld
'hello_wor'
>>> 
>>> s.rstrip('ad') # 去除末尾字符 ad
'hello_worl' # ??? 为什么 d 被去掉了?
>>> 

问题解决

在查了N多的中文参考资料之后,一直没找到出现此现象的原因,于是我拜读了一下python官方的文档:https://docs.python.org/2/library/string.html
官方文档的说明是:Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.
简单的翻译一下,其意思就是去掉字符串末尾的指定字符,如果传入的字符为空,则去掉字符串末尾的空格,但是我们忽略了重点内容:the characters in the string will be stripped from the end of the string this method is called on,这里面有两个the string,第一个the string指的是用户传入的字符串,如上面的dldad,而第二个the string指的是需要处理的string,这样理解之后,rstrip的功能就彻底明确了,其功能准确的描述就是:删除字符串末尾指定的字符中任意字符,如果为空,则删除字符串末尾的空格
提到了rstrip,就不得不提起lstrip,lstrip和rstrip功能类似,唯一的区别就是rstrip去掉的是字符串末尾的指定字符,而lstrip去掉的是字符开头的指定字符。

总结一下

rstrip和lstrip方法删除的不是传入的整个字符,而是以单个字符为单位删除,如果你传入了一段字符串,如果这段字符串中任何一个字符出现在需删除字符串的开头或末尾,则都将会被删除。如:

>>> s = 'helloworlld'
>>> s.rstrip('ld')
'hellowor'
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值