Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why tuple is being used in string format

Tags:

python

syntax

I came across code like

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

I was wondering, is there any reason of not writing them in

print "Users connected: %d" % userCount

They seem having the same output

like image 462
Cheok Yan Cheng Avatar asked Dec 12 '22 18:12

Cheok Yan Cheng


1 Answers

The code without an explicid tuple may bite you if your variable contains a tuple.

>>> 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

So always using a tuple in format string syntax is a part of defensive coding.

like image 149
max Avatar answered Dec 29 '22 14:12

max