Home >Backend Development >Python Tutorial >How to Insert a Variable into a String in Python?
How to Interpolate a Variable into a String in Python
When working with Python strings, it's often necessary to include the value of a variable within the string. This is known as string interpolation.
The Problem:
Consider the following code:
num = 40 plot.savefig('hanning40.pdf') # This line is problematic
Here, we want to save the plot using a file name that includes the value of num. However, simply inserting the variable like this doesn't work.
The Solution:
There are several methods to interpolate a variable into a string in Python:
1. f-strings:
plot.savefig(f'hanning{num}.pdf')
This method uses f-strings, which were introduced in Python 3.6. It's the preferred and most concise way to interpolate variables.
2. str.format():
plot.savefig('hanning{0}.pdf'.format(num))
This method uses the format() method of the string class. The {} placeholder represents the position of the variable in the format string.
3. String Concatenation:
plot.savefig('hanning' + str(num) + '.pdf')
This method involves concatenating the string with the string representation of the variable. However, it's not as efficient or readable as the other methods.
4. Conversion Specifier:
plot.savefig('hanning%s.pdf' % num)
This method uses a conversion specifier (%s) to represent the variable. It's similar to string concatenation but uses a more compact syntax.
5. Local Variable Names (Neat Trick):
plot.savefig('hanning%(num)s.pdf' % locals())
This trick involves passing the local variable dictionary to the format string. It allows you to use the variable name as a placeholder within the string.
6. string.Template:
plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
This method uses the string.Template class to interpolate variables. It offers advanced formatting options, but it's less commonly used than the other methods.
Additional Notes:
The above is the detailed content of How to Insert a Variable into a String in Python?. For more information, please follow other related articles on the PHP Chinese website!