python strip strips more than asked for

Viewed 226
'10000.0'.strip('.0')

is expected to return '10000' but returns only '1'. Is the expectation wrong or is the result wrong ?

It behaves properly if the string ends as 'x.0' where x is anything other than 0. Also, this strange result is consistent for '[a-zA-Z0-9]x{n}.x{n}' for any x and any n>0 .

So what it does is, it strips not only what follows the dot, but before too. If this is what strip is programmed to do, somehow it doesn't align with my expectation.

2 Answers

The strip function doesnt work the way you are expecting.

For instance, your cmd is '10000.0'.strip('.0'):

This means, you are asking it to remove all characters from front/back of the string that either match "." or "0"

This recursively removes characters from the string if they match with these characters. Which is why you see the output as 1.

For example, the output for 11000.0 would be 11

Alternatives: replace? or int() function?

  1. int(float(10000.0)) = 10000

  2. '10000.0'.replace('.0', '') = '10000'

This is according to the Docs

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. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped

In this case you'd better use round:

s='10000.0'
print(str(round(float(s))))
Related