print variable and a string in python

user203558 picture user203558 · Dec 26, 2012 · Viewed 371.8k times · Source

Alright, I know how to print variables and strings. But how can I print something like "My string" card.price (it is my variable). I mean, here is my code: print "I have " (and here I would like to print my variable card.price).

Answer

Martijn Pieters picture Martijn Pieters · Dec 26, 2012

By printing multiple values separated by a comma:

print "I have", card.price

The print statement will output each expression separated by spaces, followed by a newline.

If you need more complex formatting, use the ''.format() method:

print "I have: {0.price}".format(card)

or by using the older and semi-deprecated % string formatting operator.