python - 在打印语句中输出元组内容的更快方法
问题描述
我想用这样的打印语句打印元组的内容:
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));
解决方案
您可以使用string.format
:
a = (1,2,3,4)
print("first {}, second {}, thrid {}, forth {}".format(*a))
#first 1, second 2, thrid 3, forth 4
推荐阅读
- python-3.x - 这个插入排序和冒泡排序代码的语法有什么问题?
- microsoft-teams - MSTeams 开发人员:从个人选项卡导航到不同的团队/对话
- r - 如何在RShiny中将图像放置在标题的左右角
- setup.py - 在安装时生成数据文件
- sql - 通过排名和从另一张中减去一张来获得两张发票之间的差异
- c# - MySql 连接字符串的 Sql 等价(C#)
- python - How to make pycharm use a different cuda toolkit
- jquery - jQuery:如果你不知道它在哪里或它有什么父类,如何找到一个特定的类
- c# - 序列化:无法将类型 string[][] 转换为 string[]
- python - 提取与关键字对应的最相关位置