How can I put a list when printing in python?
For example, I have the following list:
mylist = ['foo', 'bar']
I want to print it filled with up to four indices with commas. I know that I can do the following to get it as a comma and space separated list:
', '.join(mylist)
But how can I put it in four indexes using "x", so the result is as follows:
foo, bar, x, x
In [1]: l = ['foo', 'bar'] In [2]: ', '.join(l + ['x'] * (4 - len(l))) Out[2]: 'foo, bar, x, x'
['x'] * (4 - len(l))creates a list containing the correct number of entries 'x'required to be filled.
['x'] * (4 - len(l))
'x'
edit , , len(l) > 4. ['x'] * (4 - len(l)) , .
len(l) > 4
itertools:
import itertools as it l = ['foo', 'bar'] ', '.join(it.islice(it.chain(l, it.repeat('x')), 4))
Based on the recipe grouper() itertools:
grouper()
itertools
>>> L = ['foo', 'bar'] >>> ', '.join(next(izip_longest(*[iter(L)]*4, fillvalue='x'))) 'foo, bar, x, x'
It probably belongs to the "don't try it at home" category.