For Python beginners, it's not easy to search for variables and text at the same time in the print statement, so I'd like to explain it here.
Here, we will explain three methods.
Write text + variables
Use conversion specification characters such as% d and% s
Use the format function
Write text + variables
test1.py
x = 3
print "x is"+str(x)+"is"
test1.py output
'x is 3'
Don't forget to convert X to string type.
test2.py
x = 3
print "x is%d" % x
test2.py output
'x is 3'
Also, it seems that you can write as follows using locals ().
test2_1.py
x = 3
print "x is%(x)s" % locals()
test2_1.py output
'x is 3'
test3.py
x = 3
print "x is{0}is".format(x)
test3.py output
'x is 3'
test3_1.py
x = 3
print "x is{x}is".format(**locals())
test3_1.py output
'x is 3'
Personally, I find .format () useful. You don't have to worry about the type of variables in format, and if the number of variables increases, you can just increase them like {0}, {1} .... The format at the end should be (variable 1, variable 2 ...).
Addition: There was an indication on September 24, 2015, so I corrected it
Recommended Posts