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?
%s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.
Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.
Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by comma use sep=”\n” or sep=”, ” respectively.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With