Alex Rivera | Logout

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

Asked 2010-06-02T19:05:52.760
469

I would like to put an int into a string. This is what I am doing at the moment:

num = 40
plot.savefig('hanning40.pdf') #problem line

I have to run the program for several different numbers, so I'd like to do a loop. But inserting the variable like this doesn't work:

plot.savefig('hanning', num, '.pdf')

How do I insert a variable into a Python string?


See also

If you are trying to create a file path, see How can I create a full path to a file from parts (e.g. path to the folder, name and extension)? for additional techniques. It will usually be better to use code that is specific to creating paths.

If you are trying to construct an URL with variable data, do not use ordinary string formatting, because it is error-prone and more difficult than necessary. Specialized tools are available. See Add params to given URL in Python.

If you are trying to construct a SQL query, do not use ordinary string formatting, because it is a major security risk. This is the cause of "SQL injection" which costs real companies huge amounts of money every year. See for example How to use variables in SQL statement in Python? for proper techniques.

If you just want to print (output) the string, you can prepare it this way first, or if you don't need the string for anything else, print each piece of the output individually using a single call to print. See How can

Edit
Report

2 Answers

887

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:

answered 2010-06-03T02:28:27.413
8

In general, you can create strings using:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)
answered 2010-06-02T19:08:40.267

Your Answer