如何使用字符串格式化在 Python 中打印完整的元组?
pythonprogramming更新于 2024/4/11 13:06:00
当使用 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,) 符号将单值元组与表达式区分开来。