Does Python Offer String Interpolation Like Ruby?

Linda Hamilton
Release: 2024-11-08 05:25:02
Original
806 people have browsed it

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

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

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())
Copy after login
  • .format() Method:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
Copy after login
  • 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 Does Python Offer String Interpolation 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!