Home >Backend Development >Python Tutorial >Does Python Offer String Interpolation Like Ruby?

Does Python Offer String Interpolation Like Ruby?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 05:25:02937browse

Does Python Offer String Interpolation Like Ruby?

Is There a Python Equivalent to Ruby's String Interpolation?

Ruby's string interpolation allows for concise embedding of expressions in strings, as seen in the example:

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

However, Python's string concatenation may appear verbose in comparison.

Python 3.6 String Interpolation

Python 3.6 introduces literal string interpolation similar to Ruby's:

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

Pre-3.6 Alternatives

Prior to 3.6, several alternative approaches can be used:

  • % Operator:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())
  • .format() Method:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
  • 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 Does Python Offer String Interpolation 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