如何比较Python字符串格式:%与.format?

%可以采用变量或元组。因此,您必须非常明确地说明您要执行的操作。例如,如果您尝试格式化以使-

示例

my_tuple = (1, 2, 3)
"My tuple: %s" % my_tuple
You'd expect it to give the output:
My tuple: (1, 2, 3)

输出结果

但是它将抛出TypeError。为了确保它总是打印,您需要将其作为单个参数元组提供,如下所示:

"hi there %s" % (name,)   # supply the single argument as a single-item tuple

每次记住这样的警告并不是那么容易,并且可能会导致错误。.format没有这些问题。格式也比较干净。