简体   繁体   English

元组和占位符与python print()的交互?

[英]Tuple and placeholder interaction with python print()?

I have run below 4 sets of statements, and they give different result. 我运行了以下4组语句,它们给出了不同的结果。 I am unsure about the cause of the difference. 我不确定造成差异的原因。 Please see notes below - 请参阅以下注释-

Case1 情况1

'usercount' coerced to tuple, why does formatting work when it becomes a tuple? 'usercount'被强制为元组,为什么格式化成为元组后仍然有效? Is coerced the right term here? 在这里被强迫正确的术语吗?

usercount=(6)  #integer value
print ("Users connected: %d"%(usercount,))  
Users connected: 6

Case2 案例2

%s or %d makes no difference, if its a tuple, print function works the same way. %s或%d没有区别,如果它是一个元组,则打印功能的工作方式相同。

usercount=(6)
print ("Users connected: %s"%(usercount,))
Users connected: 6

Case3 案例3

'usercount' declared as tuple, print fxn works fine with %s placeholder. 'usercount'声明为元组,print fxn与%s占位符可以很好地工作。

usercount=(6,) # now tuple
print ("Users connected: %s"%(usercount,))
Users connected: (6,)

Case4 案例4

Same case %d placeholder throws an error, number required, not tuple. 相同情况下的%d占位符引发错误,需要数字,而不是元组。

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. 很高兴知道您应该将%s用作字符串%d(decimal)的数字,您可以阅读此链接以获得有关这两个信息的更好信息。
but in your cases: 但在您的情况下:

Case1: 情况1:

the usercount=(6) lines just returns an Integer value and its true way to use %d . usercount=(6)行仅返回一个Integer值及其使用%d真实方式。

Case2: 情况2:

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. usercount=(6)行仅返回一个Integer值,并且可以将其转换为字符串并进行打印,因此您也可以使用%s

Case3: 情况3:

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. usercount=(6,)行仅返回一个元组值,并且可以将其usercount=(6,)转换为字符串并进行打印,因此您也可以使用%s

Case4: 情况4:

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. usercount=(6,)行仅返回一个元组值,在这种情况下,您不能将元组转换为整数,因此您不能为此使用%d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM