简体   繁体   中英

Python - short way to unpack list for string formatting operator?

Variations of the * or ** operators don't 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?

Use format :

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

see the docs for more details about possible formatting (floats, decimal points, conversion, ..).

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

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