开发者

Why tuple is being used in string format

I came across code like

print "Users connected: %d" % (use开发者_运维百科rCount, )

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

print "Users connected: %d" % userCount

They seem having the same output


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.


in this case yes as only item is passed. If you need to pass multiple items a tuple is needed

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


Yes they have, but parenthesis is used to group variables in a such condition

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

So its the basic usage, with one or more variables...


They end being the exact same thing if you have a single variable for substitution.

From the docs:

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

If format requires a single argument, values may be a single non-tuple object Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary)


They have the same output but the code looks different. Every software developer has developed a "style" over the years based on the kind of errors they make. If you tend to forget the comma in a single-element tuple or if you write code for different versions of Python or you just want to make your life easier in case you have to add more parameters, that can lead to "I always use a tuple" as the code above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜