我遇到过这样的代码
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/