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
In each of your cases you have a str object. Its .format method returns the formatted string as a new object. Its __mod__ method, which python calls when it sees the % operator, also returns a formatted string.
Functions and methods return anonymous objects. The context where they are called decide what happens next.
"number is {num}".format(num=num)
throws the result away.
some_variable = "number is {num}".format(num=num)
assigns the result.
some_function("number is {num}".format(num=num))
calls the function with the result as a parameter. print is not a special case - python doesn't do anything special with print.
Interestingly, f-strings like f"number is {num}" is compiled into a series of instructions that build the string dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With