How do I put a variable’s value inside a string (interpolate it into the string)?

Using f-strings:

plot.savefig(f'hanning{num}.pdf')

This was added in 3.6 and is the new preferred way.


Using str.format():

plot.savefig('hanning{0}.pdf'.format(num))

String concatenation:

plot.savefig('hanning' + str(num) + '.pdf')

Conversion Specifier:

plot.savefig('hanning%s.pdf' % num)

Using local variable names (neat trick):

plot.savefig('hanning%(num)s.pdf' % locals())

Using string.Template:

plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))

See also:

Leave a Comment