2

I just learned from this answer this answer I can use format with a list:

li = [2, 3, 5, 7, 11]
print '{0} {2} {1} {4}'.format(*li) # => 2 5 3 11

Now I want to justify every element of a list. What I'm doing is:

print "{0:>12}{1:>12}{2:>12}{3:>12}".format(*PROPERTIES)

However, this isn't really convenient as the list may get larger. I am curious is this possible by using only print and format (no loops)?

Community
  • 1
  • 1
yasen
  • 1,250
  • 7
  • 13

2 Answers2

2

Yes, you can map the same str.format to every item, then str.join the results together:

>>> li = [2, 3, 5, 7, 11]
>>> print "".join(map("{0:>12}".format, li))
           2           3           5           7          11

Indeed, having looked, this is exactly what's done in the answer you linked to.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
2
li = [2, 3, 5, 7, 11]
print ('{:>12}'*len(li)).format(*li) 
        2           3           5           7          11
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321