Strange behaviour of Python strip function [duplicate]

丶灬走出姿态 提交于 2019-12-17 19:53:29

问题


Possible Duplicate:
python str.strip strange behavior

I have following piece of code:

st = '55000.0'
st = st.strip('.0')
print st

When i execute, it print only 55 but i expect it to print 55000. I thought that the dot in strip causing this as we usually escape it in Regular Expression so i also tried st = st.strip('\.0') but still is giving same results. Any ideas why it is not just striping .0 and why all zeros striped??


回答1:


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 . and 0 off both ends, so it does - and gets left with 55.

See the official String class docs for details.




回答2:


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:

st.partition('.')[0]



回答3:


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:

>>> '   spacious   '.strip()  
'spacious'  
>>> 'www.example.com'.strip('cmowz.')  
'example'  



回答4:


Because that's what strip does:

The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped




回答5:


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.




回答6:


strip works on individual characters. You told it to strip all '.' and '0' characters, and that's what it did.




回答7:


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]



来源:https://stackoverflow.com/questions/7853914/strange-behaviour-of-python-strip-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!