Home  >  Article  >  Backend Development  >  How does Python Achieve String Interpolation Similar to Ruby's #{} Syntax?

How does Python Achieve String Interpolation Similar to Ruby's #{} Syntax?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-07 04:40:02474browse

How does Python Achieve String Interpolation Similar to Ruby's #{} Syntax?

Python's Equivalent to Ruby's String Interpolation

In Ruby, string interpolation is achieved using the #{} syntax. For instance:

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

Question: Is there a comparable mechanism in Python for interpolating strings?

Answer:

Starting with Python 3.6, string interpolation syntax was introduced, resembling Ruby's #{} interpolation. In Python 3.6 and later, the f-strings syntax allows expressions to be embedded in strings, as follows:

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

Prior to Python 3.6, the % operator was commonly employed for string interpolation. The first operand is the string to be interpolated, while the second can be a "mapping" that associates field names with values to be interpolated.

To achieve string interpolation using Python's .format() method:

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))

Finally, the string.Template class provides an alternative approach:

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 does Python Achieve String Interpolation Similar to Ruby's #{} Syntax?. 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