How do I put a variable inside a string?
Oh, the many, many ways...
String concatenation:
plot.savefig('hanning' + str(num) + '.pdf')
Conversion Specifier:
plot.savefig('hanning%s.pdf' % num)
Using local variable names:
plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick
Using str.format()
:
plot.savefig('hanning{0}.pdf'.format(num)) # Note: This is the new preferred way
Using f-strings:
plot.savefig(f'hanning{num}.pdf') # added in Python 3.6
Using string.Template
:
plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
plot.savefig('hanning(%d).pdf' % num)
The %
operator, when following a string, allows you to insert values into that string via format codes (the %d
in this case). For more details, see the Python documentation:
https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to write this with a briefer syntax:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
With the example given in the question, it would look like this
plot.savefig(f'hanning{num}.pdf')