1

Let's assume I have a explicitly defined list, with a known number of (numeric) elements, say aa=[1,2,3,4,5] - and I'd like to print these in a specific string. I'm aware I can do this:

$ python
Python 2.7.6 (default, Nov 23 2017, 15:49:48) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> aa=[1,2,3,4,5]
>>> print "%dx%d+%d+%dx%d"%tuple(aa)
1x2+3+4x5

... but I'm not very fond of how the format string "%dx%d+%d+%dx%d" looks like, and I'd much rather use string.format kind of specifiers. Then, I'm aware I can use this:

>>> print "{}x{}+{}+{}x{}".format(aa[0], aa[1], aa[2], aa[3], aa[4])
1x2+3+4x5

... but I find writing all the arguments for string.format expanded as aa[0], aa[1], aa[2], aa[3], aa[4] a bit overkill, since in this case, I explicitly know I have enough {} specifiers for all the elements of the array/list, so I'd much rather just throw aa in there, as in:

>>> print "{}x{}+{}+{}x{}".format(aa)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

... but unfortunately, that doesn't work.

So, what would be a way - if there is one -, to just refer to a list like aa in the argument of string.format, without having to specifically expand each of its elements as a separate argument?

sdaau
  • 36,975
  • 46
  • 198
  • 278

0 Answers0