2013-09-27 342 views
2

通常情況下,我可以使用下面的代碼串變量,蟒蛇2.7

print "this is a test %s" % (test) 

但是內實現一個變量,它似乎並沒有工作,我不得不使用這個

from __future__ import print_function 

回答

0

如果你正在實現一個字符串使用%s

+0

我的錯,但上面的代碼不起作用。 –

+0

'test'的價值是什麼? – Benjooster

2

試試這個:

print("this is a test", test) 

或者這樣:

print("this is a test {}".format(test)) 
+0

是的,它修復了它 –

+0

@MattWalker使用'from __future__ import print_function',你現在用'print'語句替換它的函數對象。因此,只需「打印some_value%(格式化程序)」不起作用。查看有效的答案。 –

4
>>> test = '!' 
>>> print "this is a test %s" % (test) 
this is a test ! 

如果導入print_function功能,print作爲功能:

>>> from __future__ import print_function 
>>> print "this is a test %s" % (test) 
    File "<stdin>", line 1 
    print "this is a test %s" % (test) 
          ^
SyntaxError: invalid syntax 

您應該使用功能導入後調用表單。

>>> print("this is a test %s" % (test)) 
this is a test ! 

邊注

根據the documentation

str.format是在Python 3新標準,並應優先於%格式。

>>> print("this is a test {}".format(test)) 
this is a test ! 
+0

使用未來的「打印」語法,但過時的「%」格式語法而不是str.format,有點有趣。 :) –

+0

@JohnZwinck,我補充提到關於'str.format'。感謝您的評論。 – falsetru