Home > Backend Development > Python Tutorial > Does Python Have String Interpolation Like Ruby's?

Does Python Have String Interpolation Like Ruby's?

Susan Sarandon
Release: 2024-11-30 04:27:15
Original
892 people have browsed it

Does Python Have String Interpolation Like Ruby's?

Does Python Offer String Interpolation Comparable to Ruby's?

In Ruby, string interpolation allows the insertion of expressions into strings, enhancing code readability. An example of Ruby string interpolation:

name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
Copy after login

For Python developers, the equivalent string concatenation may seem verbose.

Python String Interpolation in Python 3.6 and Later

Thankfully, Python 3.6 introduces literal string interpolation similar to Ruby's. In Python 3.6 , "f-strings" enable the inclusion of expressions:

name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")
Copy after login

Pre-Python 3.6 Alternatives

Before Python 3.6, consider these options:

  • % Operator: Use the % operator for string interpolation. The first operand is the string to be interpolated, and the second can include a "mapping" that maps field names to values. A mapping can be created using locals().
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())
Copy after login
  • .format() Method: Utilize the .format() method to interpolate strings:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
Copy after login
  • string.Template Class: Employ the string.Template class for string interpolation:
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 Does Python Have String Interpolation Like Ruby's?. 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