Is there a way to interpolate variables into a python string WITHOUT using the print function?

233 views Asked by At

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?

2

There are 2 answers

0
skeetastax On BEST ANSWER

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
0
tdelaney On

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.