[英]printing string containing variables in python
我是python新手,盡管我知道打印包含字符串和變量的文本,但是我想問一個有關此的基本問題。 這是我的代碼:
x=5
print ("the value of x is ",x)
print "the value of x is",x
第一個打印命令打印('the value of x is ', 5)
,第二個打印命令, the value of x is 5
。 但是print ('hello')
和print 'hello'
打印hello
(相同),為什么呢?
因為('hello')
只是'hello'
,而不是1元組。
打印是在py2x中的聲明,不起作用。 因此,打印("the value of x is ",x)
實際上會打印一個元組:
>>> type(('hello'))
<type 'str'>
>>> type(('hello',)) # notice the trailing `,`
<type 'tuple'>
在py2x中,只需刪除()
即可獲得正確的輸出:
>>> print "the value of x is","foo"
the value of x is foo
或者您也可以導入py3x的打印功能:
>>> from __future__ import print_function
>>> print ("the value of x is","foo")
the value of x is foo
假設使用Python 2.x,則print
是一條語句,而逗號則使表達式成為一個元組,並用括號將其打印出來。 假設使用Python 3.x,則print
是一個函數,因此第一個可以正常打印,第二個是語法錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.