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

Does Python Have String Interpolation Like Ruby's?

Susan Sarandon
Susan SarandonOriginal
2024-11-30 04:27:15894browse

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}."

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

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())
  • .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()))
  • 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"))

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!

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