2

通常,我可以使用以下代码在字符串中实现变量

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

但是,它似乎不起作用,因为我不得不使用它

from __future__ import print_function
4

3 回答 3

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

If you import print_function feature, print acts as function:

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

You should use function call form after the import.

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

SIDE NOTE

According to the documentation:

str.format is new standard in Python 3, and should be preferred to the % formatting.

>>> print("this is a test {}".format(test))
this is a test !
于 2013-09-27T14:43:30.940 回答
3

尝试这个:

print("this is a test", test)

或这个:

print("this is a test {}".format(test))
于 2013-09-27T14:42:19.633 回答
0

如果您正在实现字符串,请使用%s.

于 2013-09-27T14:41:02.353 回答