Have a variable column length in printf

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun May 31 09:34:39 CEST 2009

Apologies for breaking threading, the original post to this thread is not 
on my newserver.

Cameron Pulsford wrote:

> Hello all, I'm trying to pretty print a list, so I am doing something
> like
> print '%3d' % integer

Instead of re-inventing the wheel, have you looked at the pretty-print 
module? import pprint may do what you want.

If you still need your own custom pretty-print function, then there are a 
couple of ways to accomplish what you ask:

>> only I would like that 3 to be a variable, instead of hardcoded. Is
>> this possible, or are there any other ways to accomplish this?

As others have said, you can use '*' instead of the width. Another 
alternative, for even more flexibility, is to construct the format string 

>>> fmt = '%%0%dd' % 7
>>> print fmt % 3


More information about the Python-list mailing list