简体   繁体   English

使用%和变量名在python中打印变量

[英]printing variables in python using % and variable name

I am currently learning python and would like to know how these two print statements are different? 我目前正在学习python,想知道这两个打印语句是如何不同的? I mean both perform the same action but only differ in the syntax. 我的意思是两者都执行相同的操作,但只是语法不同。 Are there any other differences? 还有其他差异吗?

a = 5
b = 'hi'

print "The number is", a, " and the text is", b

print "The number is %d and the text is %s" %(a, b)

Well, the second one will fail if the variable a is not a number. 好吧,如果变量a不是数字,第二个将失败。

>>> a='hi'
>>> b='hi'
>>> print "The number is %d and the text is %s" %(a, b)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-aa94a92667a1> in <module>()
----> 1 print "The number is %d and the text is %s" %(a, b)

TypeError: %d format: a number is required, not str

If a is always a number, they would behave very much alike, except the %d in the format forces it to be an integer, so if you have: 如果a总是一个数字,它们会表现得非常相似,除了格式中的%d强制它是一个整数,所以如果你有:

>>> a=1.2
>>> b='hi'
>>> print "The number is %d and the text is %s" %(a, b)
The number is 1 and the text is hi

You can see that it converts the number 1.2 to an integer 1 . 您可以看到它将数字1.2转换为整数1

As per the comments, another option is to use the format function , that behaves similar to your first option but using a format string : 根据评论,另一种选择是使用格式函数 ,其行为类似于您的第一个选项,但使用格式字符串

>>> a=1.2
>>> b='hi'
>>> print "The number is {} and the text is {}".format(a, b)
The number is 1.2 and the text is hi

It also allows to use named arguments: 它还允许使用命名参数:

>>> print "The number is {number} and the text is {text}".format(number=a, text=b)
The number is 1.2 and the text is hi

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

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