6

How can I pad a list when printed in python?

For example, I have the following list:

mylist = ['foo', 'bar']

I want to print this padded to four indices, with commas. I know I can do the following to get it as a comma and space separated list:

', '.join(mylist)

But how can I pad it to four indices with 'x's, so the output is like:

foo, bar, x, x
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Matthieu Cartier
  • 2,361
  • 4
  • 17
  • 15

3 Answers3

11
In [1]: l = ['foo', 'bar']

In [2]: ', '.join(l + ['x'] * (4 - len(l)))
Out[2]: 'foo, bar, x, x'

The ['x'] * (4 - len(l)) produces a list comprising the correct number of 'x'entries needed for the padding.

edit There's been a question about what happens if len(l) > 4. In this case ['x'] * (4 - len(l)) results in an empty list, as expected.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    What happens if len(l) is greater than 4? – ovgolovin Oct 10 '11 at 14:46
  • 1
    @ovgolovin: It works as expected: multiplying a sequence by a negative number yields an empty sequence (in case you're wondering, this is documented behaviour -- I'll add a link in a moment). – NPE Oct 10 '11 at 14:51
3

Another possibility using itertools:

import itertools as it

l = ['foo', 'bar']

', '.join(it.islice(it.chain(l, it.repeat('x')), 4))
eumiro
  • 207,213
  • 34
  • 299
  • 261
0

Based on the grouper() recipe from itertools:

>>> L = ['foo', 'bar']
>>> ', '.join(next(izip_longest(*[iter(L)]*4, fillvalue='x')))
'foo, bar, x, x'

It probably belongs in the "don't try it at home" category.

jfs
  • 399,953
  • 195
  • 994
  • 1,670