Is there a Python equivalent to Ruby's string interpolation?

前端 未结 9 1200
攒了一身酷
攒了一身酷 2020-11-22 17:04

Ruby example:

name = \"Spongebob Squarepants\"
puts \"Who lives in a Pineapple under the sea? \\n#{name}.\"

The successful Python string co

9条回答
  •  我在风中等你
    2020-11-22 17:59

    Python 3.6 will add literal string interpolation similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.

    name = "Spongebob Squarepants"
    print(f"Who lives in a Pineapple under the sea? {name}.")
    

    Prior to 3.6, the closest you can get to this is

    name = "Spongebob Squarepants"
    print("Who lives in a Pineapple under the sea? %(name)s." % locals())
    

    The % operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a "mapping", mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals() to map the field name name to its value as a local variable.

    The same code using the .format() method of recent Python versions would look like this:

    name = "Spongebob Squarepants"
    print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
    

    There is also the string.Template class:

    tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
    print(tmpl.substitute(name="Spongebob Squarepants"))
    

提交回复
热议问题