Reputation: 1217
If I have a 6 length list like this:
l = ["AA","BB","CC","DD"]
I can print it with:
print "%-2s %-2s %-2s %-2s" % tuple(l)
The output will be:
AA BB CC DD
But what if the list l could be in any length? Is there a way to print the list in the same format with unknown number of elements?
Upvotes: 5
Views: 7995
Reputation: 1121962
Generate separate snippets and join them:
print ' '.join(['%-2s' % (i,) for i in l])
Or you can use string multiplication:
print ('%-2s ' * len(l))[:-1] % tuple(l)
The [:-1]
removes the extraneous space at the end; you could use .rstrip()
as well.
Demo:
>>> print ' '.join(['%-2s' % (i,) for i in l])
AA BB CC DD
>>> print ' '.join(['%-2s' % (i,) for i in (l + l)])
AA BB CC DD AA BB CC DD
>>> print ('%-2s ' * len(l))[:-1] % tuple(l)
AA BB CC DD
>>> print ('%-2s ' * len(l))[:-1] % tuple(l + l)
AA BB CC DD AA BB CC DD
Timing stats:
>>> def joined_snippets(l):
... ' '.join(['%-2s' % (i,) for i in l])
...
>>> def joined_template(l):
... ' '.join(['%-2s' for i in l])%tuple(l)
...
>>> def multiplied_template(l):
... ('%-2s ' * len(l))[:-1] % tuple(l)
...
>>> from timeit import timeit
>>> l = ["AA","BB","CC","DD"]
>>> timeit('f(l)', 'from __main__ import l, joined_snippets as f')
1.3180170059204102
>>> timeit('f(l)', 'from __main__ import l, joined_template as f')
1.080280065536499
>>> timeit('f(l)', 'from __main__ import l, multiplied_template as f')
0.7333378791809082
>>> l *= 10
>>> timeit('f(l)', 'from __main__ import l, joined_snippets as f')
10.041708946228027
>>> timeit('f(l)', 'from __main__ import l, joined_template as f')
5.52706503868103
>>> timeit('f(l)', 'from __main__ import l, multiplied_template as f')
2.8013129234313965
The multiplied template option leaves the other options in the dust.
Upvotes: 11
Reputation: 304175
Another approach
' '.join(['%-2s' for i in l])%tuple(l)
I found this to be more than twice as fast as using a generator expression
' '.join('%-2s' for i in l)%tuple(l)
This is faster still
'%-2s '*len(l)%tuple(l) # leaves an extra trailing space though
Upvotes: 1
Reputation: 48599
tests = [
["AA"],
["AA", "BB"],
["AA", "BBB", "CCC"]
]
for test in tests:
format_str = "%-2s " * len(test)
print format_str
--output:--
%-2s
%-2s %-2s
%-2s %-2s %-2s
Upvotes: 0