1

I got a problem with print in python 3.x

If you remember from python 2.x, you can write code like this:

var = 224 
print "The var is %d" %(var)

and it would print out:

The var is 224

But in python 3.x it doesn't work, so who knows please help.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2903699
  • 13
  • 1
  • 3
  • 5
    Your problem is not with string interpolation but with the `print` statement. In Python 3, `print()` is now a *function*. – Martijn Pieters Oct 21 '13 at 15:14
  • It is recommended to use the `format()` function, see its usage [here](http://stackoverflow.com/a/19382774/2425215) – K DawG Oct 21 '13 at 15:24

2 Answers2

4
var = 224
print("The var is %d" % var)

Definitely have to treat print as a function with Python 3. Try it out at: http://ideone.com/U95q0L

You could also, for a simpler solution, without interpolation, do this:

print("The var is", var)

Also included that on Ideone.

sdanzig
  • 4,510
  • 1
  • 23
  • 27
  • 1
    I suppose you meant `%`, not `,` in the print statement? – Robᵩ Oct 21 '13 at 15:20
  • 1
    The `%d` only applies when using interpolation... You would just omit the argument completely in your first example... (unless you wanted a literal `%d` in there for some reason) – Jon Clements Oct 21 '13 at 15:20
  • Yep, fixed. Will upvote Rob's answer to alleviate guilt. I like Python but it's been a while. – sdanzig Oct 21 '13 at 15:25
  • @sdanzig I'd leave in the second example - it's a more convenient way of doing it... doesn't rely on a formatting string with a type, just does it all nicely and for less characters – Jon Clements Oct 21 '13 at 15:26
1

In Python 2, print is a keyword which is used in a print statement. In Python 3, print is a function name and is used just as any other function is.

In particular, print requires parenthesis around its argument list:

 print ("The var is %d" %(var))

Ref: http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function

Robᵩ
  • 163,533
  • 20
  • 239
  • 308