2

How can I call the format function with a list as arguments?

I want to do something like this:

spacing = "{:<2} "*10
l = ['A','B','C','D','E','F','G','H','I','J']
print spacing.format(l)
Oskar Persson
  • 6,605
  • 15
  • 63
  • 124

1 Answers1

4

Use the *args format:

spacing.format(*l)

This tells Python to apply each element of l as a separate argument to the .format() method.

Do note your spacing format could end up with too many or too few elements if you hardcode the count; perhaps use the length of l instead:

spacing = "{:<2} " * len(l)

or use str.join() to eliminate that last space:

spacing = ' '.join(['{:<2}'] * len(l))

Demo:

>>> l = ['A','B','C','D','E','F','G','H','I','J']
>>> spacing = ' '.join(['{:<2}'] * len(l))
>>> spacing.format(*l)
'A  B  C  D  E  F  G  H  I  J '
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @thefourtheye: the [reference documentation](http://docs.python.org/2/reference/expressions.html#calls) calls them the `*expression` and `**expression` syntax. – Martijn Pieters Oct 13 '13 at 09:22
  • I am not sure :( http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists – thefourtheye Oct 13 '13 at 09:24
  • The tutorial talks about argument unpacking, yes, but calls `*` an operator, which is technically not correct (it is not an operator). :-) – Martijn Pieters Oct 13 '13 at 09:25
  • The tutorial is a little more fluid with terms; its focus is to teach newcomers in a concise and efficient manner the basics. Exact technical terms are less important, I think. – Martijn Pieters Oct 13 '13 at 09:26
  • Agreed :) They might have mentioned `* operator` so that people can remember it by the multiplication operator. – thefourtheye Oct 13 '13 at 09:28
  • Or instead of calling `len(l)`, iterate over `l` with `spacing = ' '.join('{:<2}' for element in l)`. – PaulMcG Oct 13 '13 at 09:52
  • @PaulMcGuire: I'd spell that as `' '.join(['{:<2}' for _ in l])`, but the multiplication is faster. – Martijn Pieters Oct 13 '13 at 09:53
  • @MartijnPieters - but why the list comp instead of generator expresion? Is multiplication faster if you take out the unnecessary []'s? – PaulMcG Oct 13 '13 at 11:01
  • @Paul: See http://stackoverflow.com/a/9061024/100297; a list comp is faster when used with `str.join()`. – Martijn Pieters Oct 13 '13 at 11:04