Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #92348 > unrolled thread

Re: Cheat sheet for the new string formatting?

Started bySerhiy Storchaka <storchaka@gmail.com>
First post2015-06-08 23:48 +0300
Last post2015-06-08 23:48 +0300
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Cheat sheet for the new string formatting? Serhiy Storchaka <storchaka@gmail.com> - 2015-06-08 23:48 +0300

#92348 — Re: Cheat sheet for the new string formatting?

FromSerhiy Storchaka <storchaka@gmail.com>
Date2015-06-08 23:48 +0300
SubjectRe: Cheat sheet for the new string formatting?
Message-ID<mailman.303.1433796531.13271.python-list@python.org>
On 08.06.15 23:32, Skip Montanaro wrote:
> This is counterintuitive:
>
>  >>> "{:.3}".format(-0.00666762259822)
> '-0.00667'
>  >>> "{:.3f}".format(-0.00666762259822)
> '-0.007'
>  >>> "%.3f" % -0.00666762259822
> '-0.007'
>  >>> "{:.3s}".format(-0.00666762259822)
> ValueError Unknown format code 's' for object of type 'float'
>
> Why does the first form display five digits after the decimal point? Why
> don't floats support "{:.Ns}"? (I know I can use "{!s}".)

"{:.3}" for floats is equivalent to "{:.3g}".

 >>> "{:.3g}".format(-0.00666762259822)
'-0.00667'
 >>> "%.3g" % -0.00666762259822
'-0.00667'

Format code 's' would produce incorrect and meaningless output for floats.

 >>> "{!s:.3}".format(-0.00666762259822)
'-0.'
 >>> "%.3s" % -0.00666762259822
'-0.'
 >>> "{!s:.3}".format(-0.0000666762259822)
'-6.'
 >>> "%.3s" % -0.0000666762259822
'-6.'

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web