How can I insert a variable’s value into a Python string?

I’m trying to dynamically include a variable inside a string in Python. For example, I want to save files with names that include a number stored in a variable:

num = 40
plot.savefig('hanning40.pdf')  # Current approach works only for a fixed number

I’d like to run this in a loop with different numbers, but this doesn’t work:

plot.savefig('hanning', num, '.pdf')  # This raises an error

What’s the correct way to python variable in string so that I can include variables like num inside file names or other strings?

I’ve heard of string formatting and f-strings, but I’m not sure which approach is best here.

The most modern way is using f-strings (Python 3.6+):

num = 40
filename = f"hanning{num}.pdf"
plot.savefig(filename)

It’s readable and avoids concatenation clutter.

Another way is str.format():

filename = "hanning{}.pdf".format(num)

Useful if you want compatibility with Python <3.6.

I sometimes use % formatting for simple scripts:

filename = “hanning%d.pdf” % num

It works fine, but f-strings are usually preferred nowadays for clarity.