Reputation: 6753
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)
Upvotes: 2
Views: 346
Reputation: 1121834
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 '
Upvotes: 4