2
'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.

Rafeek
  • 41
  • 8
  • 1
    This is the behavior [described in the docs](https://docs.python.org/3.8/library/stdtypes.html?highlight=strip#str.strip). See also: https://stackoverflow.com/questions/1038824/how-do-i-remove-a-substring-from-the-end-of-a-string-in-python – Mark Nov 14 '20 at 06:58
  • 1
    https://docs.python.org/3/library/stdtypes.html#str.removesuffix – kaya3 Nov 14 '20 at 07:02
  • 2
    `.strip('.0')` means "remove all `.` and `0` characters from the beginning and end of the string". It does not mean "remove the exact string `.0`". – John Gordon Nov 14 '20 at 07:05

2 Answers2

3

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'

Serial Lazer
  • 1,667
  • 1
  • 7
  • 15
0

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))))
Wasif
  • 14,755
  • 3
  • 14
  • 34
  • i understand i was spoiled not to browse the manual than asking here. I should refer the manuals more but may not as asking here is easier than being lost in manuals.. – Rafeek Nov 14 '20 at 11:11