James B
James B

Reputation: 293

In Python 2, can I pass a list to the percent-format operator?

I have a list of things I'd like to print using a format string. In Python 3-style, using "a string".format(arg,arg,arg), this is easy. I can just replace with arguments with *mylist, like

mylist = [1,2,3]
"{} {} {}".format(*mylist)

I can't seem to make this work with the older percent-formatting. I've tried stuff like "%i %i %i" % mylist, %i %i %i" % (mylist), and %i %i %i" % (*mylist) but I just keep getting syntax errors or "not enough arguments".

Is this impossible in 2.x style?

ETA: I am changing the example above, I actually did mean list, not tuple. I'm still learning and I'm not used to having two distinct array-like constructs.

Upvotes: 6

Views: 3619

Answers (2)

falsetru
falsetru

Reputation: 369074

str % tuple should just work.

>>> mylist = (1, 2, 3)  # <---- tuple
>>> "%i %i %i" % mylist
'1 2 3'

BTW, (1, 2, 3) is a tuple literal, not a list literal.

>>> mylist = [1, 2, 3]  # <----- list
>>> "%i %i %i" % mylist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not list

If you want to make it work for list, convert the list into a tuple.

>>> "%i %i %i" % tuple(mylist)
'1 2 3'

Upvotes: 7

Cory Kramer
Cory Kramer

Reputation: 117876

If you want to print a list delimited by spaces, here is a more flexible solution that can support any number of elements

>>> l = [5,4,3,2,1]
>>> ' '.join(map(str,l))
'5 4 3 2 1'

This also works for tuples

>>> l = (5,4,3,2,1)
>>> ' '.join(map(str,l))
'5 4 3 2 1'

Upvotes: 1

Related Questions