简体   繁体   中英

List comprehension in format string? (Python)

Let's say I have a list datalist , with len(datalist) = 4 . Let's say I want each of the elements in the list to be represented in a string in this way:

s = "'{0}'::'{1}'::'{2}' '{3}'\n".format(datalist[0], datalist[1], datalist[2], datalist[3])

I don't like having to type datalist[index] so many times, and feel like there should be a more effective way. I tried:

s = "'{0}'::'{1}'::'{2}' '{3}'\n".format(datalist[i] for i in range(4))

But this doesn't work:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

Does anybody know a functioning way to achieve this efficiently and concisely?

Yes, use argument unpacking with the "splat" operator * :

>>> s = "'{0}'::'{1}'::'{2}' '{3}'\n"
>>> datalist = ['foo','bar','baz','fizz']
>>> s.format(*datalist)
"'foo'::'bar'::'baz' 'fizz'\n"
>>>

Edit

As pointed out by @AChampion you can also just use indexing inside the format string itself:

 >>> "'{0[0]}'::'{0[1]}'::'{0[2]}' '{0[3]}'\\n".format(datalist) "'foo'::'bar'::'baz' 'fizz'\\n" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM