Python's Approach to String Interpolation
While Ruby offers a convenient way to perform string interpolation, Python initially lacked a similar mechanism. In Python 3.6, however, literal string interpolation has been introduced, aligning it with Ruby's approach.
For example:
name = "Spongebob Squarepants" print(f"Who lives in a Pineapple under the sea? {name}.")
Options Pre-Python 3.6
Before Python 3.6, Python offered alternatives for string interpolation:
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"))
In conclusion, Python 3.6 provides a concise and Ruby-like method for string interpolation, while earlier Python versions offer various alternative approaches to achieve similar results.
The above is the detailed content of How did Python catch up to Ruby in String Interpolation?. For more information, please follow other related articles on the PHP Chinese website!