Search code examples
pythonstringvariablesstring-interpolation

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


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 I print multiple things (fixed text and/or variable values) on the same line, all at once? for details on both approaches.

See How can I concatenate str and int objects? for bugs caused by trying to use + to join "strings" when one of them isn't a string.


Solution

  • 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:

    printf-style String Formatting