Putting Variables into Strings: Interpolation Techniques
Inserting variables into strings is essential for dynamic text generation in programming. In Python, there are several methods to achieve this:
**f-strings:** <pre class="brush:php;toolbar:false"> num = 40 plot.savefig(f'hanning{num}.pdf') # uses f-string syntax
**str.format():** <pre class="brush:php;toolbar:false"> plot.savefig('hanning{0}.pdf'.format(num))
**String concatenation:** <pre class="brush:php;toolbar:false"> plot.savefig('hanning' + str(num) + '.pdf')
**Conversion Specifier:** <pre class="brush:php;toolbar:false"> plot.savefig('hanning%s.pdf' % num)
**Local variable names:** <pre class="brush:php;toolbar:false"> plot.savefig('hanning%(num)s.pdf' % locals())
**string.Template:** <pre class="brush:php;toolbar:false"> plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
**Looping:** <pre class="brush:php;toolbar:false"> for num in range(1, 101): plot.savefig('hanning{}.pdf'.format(num))
Each method has its own advantages and applications. Choosing the appropriate technique depends on factors such as Python version, code readability, and performance requirements.
The above is the detailed content of How Can I Efficiently Embed Variables into Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!