我遇到了类似的代码

print "Users connected: %d" % (userCount, )

我想知道,是否有任何理由不将它们写入
print "Users connected: %d" % userCount

他们似乎有相同的输出

最佳答案

如果您的变量包含一个元组,则没有显式元组的代码可能会困扰您。

>>> nums = (1, 2, 3, 4)
>>> print "debug: %r" % (nums, )
debug: (1, 2, 3, 4)
>>> print "debug: %r" % nums
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
所以总是在格式字符串语法中使用元组是防御性编码的一部分。

关于python - 为什么元组以字符串格式使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4142243/

10-14 17:40
查看更多