在 Python 中使用字符串格式打印元组

新手上路,请多包涵

所以,我有这个问题。我得到了元组 (1,2,3),我应该用字符串格式打印它。例如。

 tup = (1,2,3)
print "this is a tuple %something" % (tup)

这应该用括号打印元组表示,比如

这是一个元组 (1,2,3)

但是我得到 TypeError: not all arguments converted during string formatting

我怎么能做到这一点?有点迷路了,所以如果你们能指出我正确的方向:)

原文由 veturi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 372
2 个回答
>>> # Python 2
>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

>>> # Python 3
>>> thetuple = (1, 2, 3)
>>> print(f"this is a tuple: %s" % (thetuple,))
this is a tuple: (1, 2, 3)

将感兴趣的元组作为唯一项创建单例元组,即 (thetuple,) 部分,是此处的关键位。

原文由 Alex Martelli 发布,翻译遵循 CC BY-SA 4.0 许可协议

请注意, % 语法已过时。使用 str.format ,它更简单且更具可读性:

 t = 1,2,3
print 'This is a tuple {0}'.format(t)

原文由 Antimony 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏