Python short way to unpack list for string format operator?

Variations of the * or ** operators do not seem to work, unfortunately:

lstData = [1,2,3,4]
str = 'The %s are %d, %d, %d, and %d' % ('numbers', *lstData)

Is there an easy way?

+5
source share
3 answers

Use format :

str = 'The {} are {}, {}, {}, and {}'.format('numbers', *lstData)

see the documentation for more information on possible formatting (floats, decimal points, conversion, ..).

+7
source
s = 'The %s are %d, %d, %d, and %d' % tuple(['numbers'] + lstData)
+2
source
>>> data = range(5)
>>> 'The {0} are {1}, {2}, {3}, {4} and {5}'.format('numbers', *data)
'The numbers are 0, 1, 2, 3 and 4'
+1
source

All Articles