Home >Backend Development >Python Tutorial >Does Python Offer String Interpolation Like Ruby?
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 introduces literal string interpolation similar to Ruby's:
name = "Spongebob Squarepants" print(f"Who lives in a Pineapple under the sea? {name}.")
Prior to 3.6, several alternative approaches can be used:
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 Offer String Interpolation Like Ruby?. For more information, please follow other related articles on the PHP Chinese website!