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