[英]How to use text strip() function?
I can strip numerics but not alpha characters: 我可以剥离数字,但不能剥离字母字符:
>>> text
'132abcd13232111'
>>> text.strip('123')
'abcd'
Why the following is not working? 为什么以下内容不起作用?
>>> text.strip('abcd')
'132abcd13232111'
The reason is simple and stated in the documentation of strip
: 原因很简单,并在
strip
的文档中进行了说明 :
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed.
The chars argument is a string specifying the set of characters to be removed.
'abcd'
is neither leading nor trailing in the string '132abcd13232111'
so it isn't stripped. 'abcd'
在字符串'132abcd13232111'
既不是前导也不是尾随,因此不会被剥离。
Just to add a few examples to Jim's answer , according to .strip()
docs: 根据
.strip()
文档,仅在Jim的答案中添加一些示例:
So it doesn't matter if it's a digit or not, the main reason your second code didn't worked as you expected , is because the term "abcd" was located in the middle of the string. 因此,无论它是否是数字都没有关系,您的第二个代码未按预期工作的主要原因是因为术语“ abcd”位于字符串的中间。
Example1: 范例1:
s = '132abcd13232111'
print(s.strip('123'))
print(s.strip('abcd'))
Output: 输出:
abcd
132abcd13232111
Example2: 范例2:
t = 'abcd12312313abcd'
print(t.strip('123'))
print(t.strip('abcd'))
Output: 输出:
abcd12312313abcd
12312313
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.