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

对着背影说爱祢 提交于 2019-12-01 21:44:01

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'

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'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!