Why a tuple is used in a string format

I came across a code like

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

I was wondering if there was a reason not to write them in

 print "Users connected: %d" % userCount 

They seem to have the same conclusion.

+4
source share
5 answers

Code without an explanatory 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 

Therefore, always using a tuple in the format string syntax is part of the security coding.

+14
source

They end in the same way if you have a single variable to substitute.

From docs :

Given format % values (in your case format = "Users are connected:% d" and values = userCount)

If a format requires a single argument, the values ​​may be single object tuples. Otherwise, the values ​​must be a tuple with exactly the number of positions specified by the format string, or a single matching object (for example, a dictionary)

0
source

in this case, yes, since only the element is transmitted. If you need to pass multiple elements, you need a tuple

 print 'There are %d user connected %s' % (userCount, 'today') 
0
source

Yes, they do, but brackets are used to group variables in this condition

 print "Hi there. I am %s and i am %d years old"%(name, age) 

So this is the main use with one or more variables ...

0
source

They have the same output, but the code looks different. Each software developer has developed a β€œstyle” over the years based on the mistakes they create. If you are trying to forget the comma in a singleton tuple, or if you are writing code for different versions of Python, or just want to make your life easier if you need to add additional parameters, this can lead to the fact that I always use the tuple "as the code above.

-1
source

All Articles