首页 > 解决方案 > Is there a way to insert a list into the .format method in python?

问题描述

I want to do something like:

list = [1,2,3]
valstring = "one: {}, two: {}, three: {}".format(list)
print(valstring)

result:

one: 1, two: 2, three: 3

Is something like this possible? I know I can achieve a similar result by using .format(list[0], list[1], list[2]) but I have a long list so I'd prefer not to.

标签: pythonlistprintingstring.format

解决方案


是的,使用星号( Python 中*所谓的“解包”):

lst = [1,2,3]
valstring = "one: {}, two: {}, three: {}".format(*lst)
print(valstring)

印刷:

one: 1, two: 2, three: 3

推荐阅读