我目前正在学习python,想知道这两个打印语句有何不同?我的意思是两者都执行相同的操作,但只是语法不同。还有其他差异吗?
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)
答案 0 :(得分:2)
如果变量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
如果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
您可以看到它将数字1.2
转换为整数1
。
根据评论,另一个选项是使用format function,其行为类似于您的第一个选项但使用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
它还允许使用命名参数:
>>> 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