printing – print variable and a string in python
printing – print variable and a string in 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.
Something that (surprisingly) hasnt 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. Dont use that.
printing – print variable and a string in python
If you are using python 3.6 and newer then you can use f-strings to do the task like this.
print(fI 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.