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 *my
Solution 1:
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'
Solution 2:
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'
Post a Comment for "In Python 2, Can I Pass A List To The Percent-format Operator?"