Home >Backend Development >Python Tutorial >How Can I Efficiently Insert Variables into Strings in Python?
String Interpolation in Python
When working with variables and strings in Python, it becomes necessary to insert the variable's value into the string. There are multiple methods to achieve this, catering to different versions and preferences.
f-Strings (Python 3.6 and later)
This is the preferred method for modern Python versions. It allows for seamless insertion using curly braces.
plot.savefig(f'hanning{num}.pdf')
str.format() Method
This method formats the string using positional placeholders (%s) or named placeholders (%(placeholder_name)s).
plot.savefig('hanning{0}.pdf'.format(num))
String Concatenation
Concatenating the string with the converted variable value is an alternative approach.
plot.savefig('hanning' + str(num) + '.pdf')
Conversion Specifier
This syntax uses a conversion character followed by the placeholder in parentheses.
plot.savefig('hanning%s.pdf' % num)
Using Local Variable Names (Local Scope Trick)
A clever technique allows for referencing local variables directly in the formatting.
plot.savefig('hanning%(num)s.pdf' % locals())
string.Template Class
This class can perform substitution on a string template.
plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
By utilizing these methods, you can seamlessly integrate variable values into strings, enabling advanced string manipulations and dynamic output generation.
The above is the detailed content of How Can I Efficiently Insert Variables into Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!