View list in format string? (Python)

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

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

I donโ€™t like to type datalist[index]so many times and I feel that there should be a more efficient way. I tried:

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

But this does not work:

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

Does anyone know which way to achieve this effectiveness?

+4
source share
1 answer

Yes, use unpacking arguments 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 index inside the format string itself:
>>> "'{0[0]}'::'{0[1]}'::'{0[2]}' '{0[3]}'\n".format(datalist)
"'foo'::'bar'::'baz' 'fizz'\n"
+4

Source: https://habr.com/ru/post/1684329/


All Articles