3

Normally, i can use the following code to implement a variable within a string

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

however, it doesn't seem to work as i had to use this

from __future__ import print_function

3 Answers 3

5
>>> 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 !
Sign up to request clarification or add additional context in comments.

2 Comments

It's a bit funny to use the futuristic "print" syntax but the obsolete "%" format syntax instead of str.format. :)
@JohnZwinck, I add mention about str.format. Thank you for comment.
4

Try this:

print("this is a test", test)

Or this:

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

1 Comment

@MattWalker With from __future__ import print_function, you now replace the print statement with its function counterpart. Thus, simply print some_value % (formatter) doesn't work. See the answers for what works.
0

If you're implementing a string use %s.

1 Comment

What is the value of test?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.