Every example I have seen of Python string variable interpolation uses the print
function.
For example:
num = 6
# str.format method
print("number is {}".format(num))
# % placeholders
print("number is %s"%(num))
# named .format method
print("number is {num}".format(num=num))
Can you interpolate variables into strings without using print
?
Ok...so, it's kind of easy.
The old method:
num = 6
mystr = 'number is %s' % num
print(mystr) # number is 6
The newer .format
method:
num = 6
mystr = "number is {}".format(num)
print(mystr) # number is 6
The .format
method using named variable (useful for when sequence can't be depended upon):
num = 6
mystr = "number is {num}".format(num=num)
print(mystr) # number is 6
The shorter f-string
method: (thank you @mayur)
num = 6
mystr = f"number is {num}"
print(mystr) # number is 6