Home >Backend Development >Python Tutorial >How can I achieve string interpolation in Python like Ruby?

How can I achieve string interpolation in Python like Ruby?

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 08:17:03907browse

How can I achieve string interpolation in Python like Ruby?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn