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
Release: 2024-11-16 08:17:03
Original
884 people have browsed it

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}.")
Copy after login

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())
Copy after login

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()))
Copy after login

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"))
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template