How to Interpolate Variables into Strings in Python
When constructing strings dynamically, it's often necessary to include values stored in variables. Python offers several methods to achieve this interpolation:
1. F-strings (Python 3.6 ):
F-strings provide a concise and modern way to insert variables into strings:
num = 40 plot.savefig(f'hanning{num}.pdf')
2. str.format():
str.format() allows for flexible formatting and variable substitution:
plot.savefig('hanning{0}.pdf'.format(num))
3. String Concatenation:
Concatenating strings with variables (converted to strings):
plot.savefig('hanning' + str(num) + '.pdf')
4. Conversion Specifier:
Using the % operator to specify variable type and position:
plot.savefig('hanning%s.pdf' % num)
5. Local Variable Names Trick:
Inserting local variable names into the formatting string:
plot.savefig('hanning%(num)s.pdf' % locals())
6. string.Template:
Using string.Template for more advanced formatting needs:
plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
Additional Tips:
The above is the detailed content of How to Efficiently Interpolate Variables into Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!