[python] print variable and a string in python

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

This question is related to python printing

The answer is


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.


Assuming you use Python 2.7 (not 3):

print "I have", card.price (as mentioned above).

print "I have %s" % card.price (using string formatting)

print " ".join(map(str, ["I have", card.price])) (by joining lists)

There are a lot of ways to do the same, actually. I would prefer the second one.


Something that (surprisingly) hasn't been mentioned here is simple concatenation.

Example:

foo = "seven"

print("She lives with " + foo + " small men")

Result:

She lives with seven small men

Additionally, as of Python 3, the % method is deprecated. Don't use that.


All answers above are correct, However People who are coming from other programming language. The easiest approach to follow will be.

variable = 1

print("length " + format(variable))


If you are using python 3.6 and newer then you can use f-strings to do the task like this.

print(f"I have {card.price}")

just include f in front of your string and add the variable inside curly braces { }.

Refer to a blog The new f-strings in Python 3.6: written by Christoph Zwerschke which includes execution times of the various method.


From what I know, printing can be done in many ways

Here's what I follow:

Printing string with variables

a = 1
b = "ball"
print("I have", a, b)

Versus printing string with functions

a = 1
b = "ball"
print("I have" + str(a) + str(b))

In this case, str() is a function that takes a variable and spits out what its assigned to as a string

They both yield the same print, but in two different ways. I hope that was helpful


'''

If the python version you installed is 3.6.1, you can print strings and a variable through
a single line of code.
For example the first string is "I have", the second string is "US
Dollars" and the variable, **card.price** is equal to 300, we can write
the code this way:

'''

print("I have", card.price, "US Dollars")

#The print() function outputs strings to the screen.  
#The comma lets you concatenate and print strings and variables together in a single line of code.