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.
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.
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.
Printing string and integer (or float) in the same line
How to print a variable and a string at once in Python 3
In the title how do I print both a static string and a varaible at once, I tried doing it like this:
print ("The year of birth for ") (person)
But it gave me a notype error. But that makes no sense to me as this program has no functions and the variable was defined and worked fine earlier in the program. Can someone help?
There is a class called StringIO, which does what you described.
import io
string_out = io.StringIO()
string_out.write('Foo')
if some_condition:
string_out.write('Bar')
string_out.getvalue() # Could be 'Foo' or 'FooBar'
the io module allows exactly that: use the versatility of the print() function with the flux redirected to a string.
from io import StringIO
output = StringIO()
print("Hello World!", file=output)
print(f"I have written so far this to my string: {output.getvalue()}", file=output)
result = output.getvalue()
print(result)
outputs:
Hello World!
I have written so far this to my string: Hello World!
You cannot overuse this technique. See this example:
from io import StringIO
garbage = StringIO()
def foo(stuff, out_flux=None):
''' A function that prints stuff but you need to mute from time to time. '''
result = stuff
print(result, file=out_flux)
# normal use
foo(10) # prints 10
# muted use
foo(10, out_flux=garbage) # prints nothing
print(garbage.getvalue()) # prints whatever was collected so far