2013-09-27 352 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