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.