I have run below 4 sets of statements, and they give different result. I am unsure about the cause of the difference. Please see notes below -
'usercount' coerced to tuple, why does formatting work when it becomes a tuple? Is coerced the right term here?
usercount=(6) #integer value
print ("Users connected: %d"%(usercount,))
Users connected: 6
%s or %d makes no difference, if its a tuple, print function works the same way.
usercount=(6)
print ("Users connected: %s"%(usercount,))
Users connected: 6
'usercount' declared as tuple, print fxn works fine with %s placeholder.
usercount=(6,) # now tuple
print ("Users connected: %s"%(usercount,))
Users connected: (6,)
Same case %d placeholder throws an error, number required, not tuple.
usercount=(6,)
print ("Users connected: %d"%(usercount,))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-59-02d2ce66d935> in <module>()
1 usercount=(6,)
----> 2 print ("Users connected: %d"%(usercount,))
TypeError: %d format: a number is required, not tuple
Also, both placeholders work, when tuple declared the other way.
usercount=(6,)
print ("Users connected: %s"%(usercount))
Users connected: 6
usercount=(6,)
print ("Users connected: %d"%(usercount))
Users connected: 6
Its good to know that you should use %s for strings %d(decimal) for numbers, you can read this Link for getting better information about these two.
but in your cases:
the usercount=(6)
lines just returns an Integer value and its true way to use %d
.
the usercount=(6)
lines just returns an Integer value and its can be casted to string and printed so you can use %s
for that too.
the usercount=(6,)
lines just returns a Tuple value and its can be casted to string and printed so you can use %s
for that too.
the usercount=(6,)
lines just returns a Tuple value and in this case you can not cast a tuple to an Integer so you cant use %d
for that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.