如何使用字符串格式化在 Python 中打印一个完整的元组?
在 Python 中使用旧式字符串格式化,即 "" % (),如果百分号后面的内容是元组,Python 会尝试将其分解,并将各个项目传递到字符串中。例如,
tup = (1,2,3)
print("this is a tuple %s" % (tup))会给出以下输出
TypeError: not all arguments converted during string formatting
这是由于上述原因造成的。如果您想要传递一个元组,您需要使用 (tup, ) 语法创建一个包装元组。例如,
tup = (1,2,3)
print("this is a tuple %s" % (tup, ))会给出以下输出
this is a tuple (1, 2, 3)
(tup, ) 符号将单值元组与表达式区分开来。
广告
数据结构
计算机网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP