How do I put a variable’s value 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 preferred way since 3.6

Using f-strings:

plot.savefig(f'hanning{num}.pdf') # added in Python 3.6

This is the new preferred way:


Using string.Template:

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

Leave a Comment