4

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
  • 1
    could just use `int(round(float(st)))` – John Riselvato Oct 21 '11 at 18:53
  • +1 to @KennyTM - quick description is that `strip()` removes any characters specified in its argument from the beginning and end of a string, and returns a new string without those characters. – wkl Oct 21 '11 at 18:53
  • 1
    In python 3.9, you can do `st = st.removesuffix('.0')`. More on this: https://stackoverflow.com/a/64295844/1465553 – Saurav Sahu Oct 10 '20 at 16:44

7 Answers7

9

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.

declension
  • 4,110
  • 22
  • 25
5

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'  
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
5

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]
Scott A
  • 7,745
  • 3
  • 33
  • 46
2

Because that's what strip does:

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

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

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.

kojiro
  • 74,557
  • 19
  • 143
  • 201
1

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

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
1

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]

sdhull
  • 11
  • 1