[Tutor] variable length precision

Wayne srilyk at gmail.com
Tue Jun 23 01:25:57 CEST 2009


Well, I was going to ask the question, but some experimentation has led me
to the answer which I will share. Mainly because I'm sure someone out there
may come across the need.

I'm writing a function that will generate me a filename such as

"file0001.jpg"

but I want to be able to specify the minimum length - so it could be
"file01.jpg" or "file00000001.jpg"

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'

Hope this helps someone!
-Wayne
-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090622/15b766e1/attachment.htm>


More information about the Tutor mailing list