Home > Article > Backend Development > How does Python Achieve String Interpolation Similar to Ruby's #{} Syntax?
In Ruby, string interpolation is achieved using the #{} syntax. For instance:
name = "Spongebob Squarepants" puts "Who lives in a Pineapple under the sea? \n#{name}."
Question: Is there a comparable mechanism in Python for interpolating strings?
Answer:
Starting with Python 3.6, string interpolation syntax was introduced, resembling Ruby's #{} interpolation. In Python 3.6 and later, the f-strings syntax allows expressions to be embedded in strings, as follows:
name = "Spongebob Squarepants" print(f"Who lives in a Pineapple under the sea? {name}.")
Prior to Python 3.6, the % operator was commonly employed for string interpolation. The first operand is the string to be interpolated, while the second can be a "mapping" that associates field names with values to be interpolated.
To achieve string interpolation using Python's .format() method:
name = "Spongebob Squarepants" print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
Finally, the string.Template class provides an alternative approach:
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 How does Python Achieve String Interpolation Similar to Ruby's #{} Syntax?. For more information, please follow other related articles on the PHP Chinese website!