Python's Equivalent to Ruby's String Interpolation
Ruby's string interpolation, which allows for easy inclusion of expressions within a string, has a Python equivalent in various forms.
Format String Interpolation (f-strings)
Python 3.6 and later introduced "f-strings," which enable literal string interpolation. Expressions can be directly inserted using the syntax:
name = "Spongebob Squarepants" print(f"Who lives in a Pineapple under the sea? {name}.")
String Interpolation with the % Operator
Prior to Python 3.6, string interpolation can be achieved using the % operator. The first operand is the string to be interpolated, while the second operand can be a mapping that matches field names to values. For example:
name = "Spongebob Squarepants" print("Who lives in a Pineapple under the sea? %(name)s." % locals())
String Interpolation with .format() Method
Recent Python versions also provide the .format() method for string interpolation:
name = "Spongebob Squarepants" print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
String.Template Class
Another option is to use the string.Template class:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.") print(tmpl.substitute(name="Spongebob Squarepants"))
The above is the detailed content of How can I achieve string interpolation in Python like Ruby?. For more information, please follow other related articles on the PHP Chinese website!