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?

7
  • 2
    .format(*aa)? Commented Dec 20, 2017 at 9:42
  • 2
    you need "{}x{}+{}+{}x{}".format(*aa) to unpack the elements Commented Dec 20, 2017 at 9:42
  • Jeez, thanks guys - that is what I needed; if any of you wants to post an answer, I'll accept it; cheers! Duplicate is fine, too... Commented Dec 20, 2017 at 9:43
  • 1
    @sdaau no need since it's a duplicate. Of course you can always upvote the answer(s) in the original question(s) :) Commented Dec 20, 2017 at 9:45
  • 2
    @Jean-FrançoisFabre I'm not that picky; I've no doubt there are plenty of others, too. Commented Dec 20, 2017 at 9:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.