有没有办法打印出嵌入句子中的列表的值而不单独调用它们的值?例如,而不是这样做:
test = ["baseball","brother","sister"]
print ("Bob went out to play {} with his {} and {}.".format(test[0], test[1], test[2])).
是否有办法将其缩短为:
print ("Bob went out to play {} with his {} and {}.".format(test[0:2]))
正如Paul Panzer在问题评论中指出的那样,您可以在前面使用*
,尽管您需要*test[0:3]
而不是*test[0:2]
:
test = ["baseball","brother","sister"]
print ("Bob went out to play {} with his {} and {}.".format(*test[0:3]))
这会产生:
Bob went out to play baseball with his brother and sister.