print variable and a string in python
PythonPrintingPython Problem Overview
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)
.
Python Solutions
Solution 1 - Python
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.
Solution 2 - Python
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.
Solution 3 - Python
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.
Solution 4 - Python
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.
Solution 5 - Python
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
Solution 6 - Python
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.pricè 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.