String formatting with floats... can't get it!

Gary Herron gherron at islandtraining.com
Wed Mar 24 13:02:00 EST 2004


On Wednesday 24 March 2004 09:44 am, Batista, Facundo wrote:
> With an int:
> >>> '%d' % 4
>
> '4'
>
> >>> '%.2d' % 4
>
> '04'
>
> >>> '%2d' % 4
>
> ' 4'
>
> >>> '%2.2d' % 4
>
> '04'
>
> But with a float:
> >>> '%f' % 2.33
>
> '2.330000'
>
> >>> '%.2f' % 2.33
>
> '2.33'
>
> >>> '%2.f' % 2.33
>
> ' 2'
>
> >>> '%2.2f' % 2.33
>
> '2.33'
>
> Why in this last line I don't get ' 2.33'?

Use '%5.2f'.  The first digit is the total length of the result you
want (5 characters), while the second digit is how many of those
characters are used for the portion after the point.  Thus '%2.2f'
does not make any sense, so the first '2' is ignored and the formating
uses whatever it needs.

Gary Herron






More information about the Python-list mailing list