为什么元组以字符串格式使用

Che*_*eng 4 python syntax

我遇到过类似的代码

print "Users connected: %d" % (userCount, )
Run Code Online (Sandbox Code Playgroud)

我在想,有什么理由不写它们

print "Users connected: %d" % userCount
Run Code Online (Sandbox Code Playgroud)

他们似乎有相同的输出

max*_*max 14

如果您的变量包含元组,那么没有明确元组的代码可能会咬你.

>>> 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
Run Code Online (Sandbox Code Playgroud)

因此,始终在格式字符串语法中使用元组是防御性编码的一部分.