[Tutor] cut all decimal places with zeros

John Fouhy john at fouhy.net
Wed Apr 16 01:45:33 CEST 2008


On 16/04/2008, Tim Michelsen <timmichelsen at gmx-topmail.de> wrote:
> Kent wrote:
>  > I don't know how to do this with just string formatting but I think
>  > ('%.4f' % n).rstrip('.0')
>  > will do what you want.
>
> No.
>  I tested with
>  n = 10.0
>  You code returns '1'
>
>  My code returns '10'

Good catch.  Try:

('%.4f' % n).rstrip('0').rstrip('.')

You can read about the rstrip function by starting the python
interpreter, then typing
  help(''.rstrip)

This will explain that rstrip will strip off any charcters in the
argument from the right of the string you call it on.

So '10.0'.rstrip('.0') will remove any '.' or '0' from the right, leaving '1'.

'10.0'.rstrip('0') will remove '0' only, leaving '10.'.  Thus
'10.0'.rstrip('0').rstrip('.') will remove the '0's, then remove the
'.'s, leaving '10'.

-- 
John.


More information about the Tutor mailing list