variable length print format

Steve Holden sholden at holdenweb.com
Tue May 7 17:26:51 EDT 2002


"les ander" <les_ander at yahoo.com> wrote ...
> Hi,
> i have a variable length list of numbers.
> i would like to print them out with indicies in front as shown below:
>
> List=['a','b','c','d'] ---> 1:a 2:b 3:c 4:d
>
> one obvious solution is that i do
> for i in range(List):
>   print "%s:%s" % (i+1,List[i])
>
> however i have a lot of these and would like it to be faster so i
> tried doing this
>
> formatstr=" %s:%s " * len(List)
>
> print formatstr % (range(1,len(List)+1), List)
>
> but it did not work.
>
> is there a way to do this another way?

One way is to put the integer indexes into the format string, then just
format a tuple built from the list:

>>> aList = ['a', 'b', 'c', 'd']
>>> format = ""
>>> for i in range(len(aList)):
...     format = "%s %d: %%s" % (format, i+1)
### Note: the double "%" becomes a percent sign in the output
...
>>> format
' 1: %s 2: %s 3: %s 4: %s'
>>> print format % tuple(aList)
 1: a 2: b 3: c 4: d

You could ring the variations on this, but the basic idea is the same. Also
note that you cannot write

    for i in range(aList):

- the arguments to the range() built-in should be integers.

regards
 Steve
--

Steve Holden: http://www.holdenweb.com/ ; Python Web Programming:
http://pydish.holdenweb.com/pwp/








More information about the Python-list mailing list