簡體   English   中英

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

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

我目前正在學習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)

好吧,如果變量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

根據評論,另一種選擇是使用格式函數 ,其行為類似於您的第一個選項,但使用格式字符串

>>> 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM