Python strip 函数的奇怪行为
我有这样的代码:
st = '55000.0'
st = st.strip('.0')
print st
我期望它打印 55000
,但它却打印 55
。 我认为参数中的 .
可能需要转义(就像在正则表达式中一样);所以我也尝试了st = st.strip('\.0')
,但结果是一样的。
为什么从输入中删除所有零?为什么删除.0
后不停止?
I have this code:
st = '55000.0'
st = st.strip('.0')
print st
I expected it to print 55000
, but instead it prints 55
.
I thought perhaps the .
in the argument might need to be escaped (like in a regular expression); so I also tried st = st.strip('\.0')
, but the result is the same.
Why are all the zeros removed from the input? Why doesn't it stop after removing the .0
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您误解了 strip() - 它从两端删除任何指定字符;这里没有正则表达式支持。
您要求它从两端剥离
.
和0
,它会这样做 - 并留下55
。有关详细信息,请参阅官方 String 类文档。
You've misunderstood strip() - it removes any of the specified characters from both ends; there is no regex support here.
You're asking it to strip both
.
and0
off both ends, so it does - and gets left with55
.See the official String class docs for details.
请参阅
str.strip
上的文档,重要的部分是:chars 参数不是前缀或后缀;相反,它的值的所有组合都会被删除:
See the documentation on
str.strip
, the important part being:The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
因为您告诉它删除所有句点和 0,所以它会一直向上到第一个非句点、非 0 字符。
Strip 使用字符列表,而不是它们的特定配置。
尝试这样的事情:
Because you're telling it to strip all periods and 0s, so it keeps going up to the first non-period, non-0 character.
Strip uses a list of characters, not a specific configuration of them.
Try something like this instead:
因为这就是
strip
的作用:Because that's what
strip
does:因为
strip
的参数是要删除的字符集,而不是要删除的字符串。换句话说。它从该字符串末尾删除该集合中任意位置的每个字符,直到遇到不在该集合中的字符。Because the argument to
strip
is the set of characters to be removed, not the string to be removed. In other words. It removes each character from the ends of that string that are anywhere in the set, until it encounters a character not in that set.strip
适用于单个字符。你告诉它删除所有“.”和“0”字符,这就是它所做的。strip
works on individual characters. You told it to strip all '.' and '0' characters, and that's what it did.请参阅 http://docs.python.org/library/stdtypes.html#string -formatting
[chars] 参数列出了必须从字符串中删除的字符集!
要获得所需的结果 5500,请使用
a.split('.0')[0]
Refer to http://docs.python.org/library/stdtypes.html#string-formatting
The [chars] arguments lists the SET of characters that must be removed from the string!
To get the desired result of 5500, use
a.split('.0')[0]