[Tutor] variable length precision

Kent Johnson kent37 at tds.net
Tue Jun 23 02:48:48 CEST 2009


On Mon, Jun 22, 2009 at 7:25 PM, Wayne<srilyk at gmail.com> wrote:

> With string formatting I know you can easily specify precision a la
> 'file%.2d.jpg' % 1 which would give me 'file01.jpg' but then I discovered
> you can indeed chain together formatting (or use variables in place of
> string constants... of course some of us know that string objects really are
> references to constant strings...) - you just have to add %% where you want
> the final one:
>
> In [45]: 'some numbers %%.%sd' % 8 % 4
> Out[45]: 'some numbers 00000004'

Even simpler - you can use a * for the field width or precision, which
means, take the width or precision from the argument list:

In [12]: 'some numbers %.*d' % (8, 4)
Out[12]: 'some numbers 00000004'

In [13]: 'some numbers %*.*d' % (12, 8, 4)
Out[13]: 'some numbers     00000004'

Kent


More information about the Tutor mailing list