首页 > 解决方案 > 在打印语句中输出元组内容的更快方法

问题描述

我想用这样的打印语句打印元组的内容:

print("First value: %i, Next four values: %i %i %i %i, Next three values: %i %i %i\n" % (myTuple[0], myTuple[1], myTuple[2], myTuple[3], myTuple[4], myTuple[5], myTuple[6], myTuple[7]));

现在正如您在上面的示例中看到的那样,元组中的元素将按顺序输出,但格式使得您不能轻易使用循环。有没有办法只在 print 语句中指定整个元组/列表/集合(或给定范围)而不单独指定每个元素,像这样?

 print("First value: %i, Next four values: %i %i %i %i, Next three values: %i %i %i\n" % (myTuple[:7));

标签: pythontuples

解决方案


您可以使用string.format

a = (1,2,3,4)
print("first {}, second {}, thrid {}, forth {}".format(*a))
#first 1, second 2, thrid 3, forth 4

推荐阅读