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

前端 未结 9 1100
攒了一身酷
攒了一身酷 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:39

    You can also have this

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

    http://docs.python.org/2/library/string.html#formatstrings

    0 讨论(0)
  • 2020-11-22 17:41

    Since Python 2.6.X you might want to use:

    "my {0} string: {1}".format("cool", "Hello there!")
    
    0 讨论(0)
  • 2020-11-22 17:44

    Python's string interpolation is similar to C's printf()

    If you try:

    name = "SpongeBob Squarepants"
    print "Who lives in a Pineapple under the sea? %s" % name
    

    The tag %s will be replaced with the name variable. You should take a look to the print function tags: http://docs.python.org/library/functions.html

    0 讨论(0)
  • 2020-11-22 17:45

    Python 3.6 and newer have literal string interpolation using f-strings:

    name='world'
    print(f"Hello {name}!")
    
    0 讨论(0)
  • 2020-11-22 17:46

    For old Python (tested on 2.4) the top solution points the way. You can do this:

    import string
    
    def try_interp():
        d = 1
        f = 1.1
        s = "s"
        print string.Template("d: $d f: $f s: $s").substitute(**locals())
    
    try_interp()
    

    And you get

    d: 1 f: 1.1 s: s
    
    0 讨论(0)
  • 2020-11-22 17:47

    I've developed the interpy package, that enables string interpolation in Python.

    Just install it via pip install interpy. And then, add the line # coding: interpy at the beginning of your files!

    Example:

    #!/usr/bin/env python
    # coding: interpy
    
    name = "Spongebob Squarepants"
    print "Who lives in a Pineapple under the sea? \n#{name}."
    
    0 讨论(0)
提交回复
热议问题