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?
With the "%" operator, we can insert a variable into a string.
Instead of using quotes (double quotes or single quotes), we use template literals defined with the backticks (` character in keyboard). We place the string in the backticks and embed our variables in the sentence. Following are the usages of template literals.
You write the string as normal but for the variable you want to include in the string, you write the variable like this: ${variableName} . For the example above, the output will be the same as the example before it that uses concatenation. The difference is, the interpolation example is much easier to read.
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()))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With