Ruby example:
name = \"Spongebob Squarepants\"
puts \"Who lives in a Pineapple under the sea? \\n#{name}.\"
The successful Python string co
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
Since Python 2.6.X you might want to use:
"my {0} string: {1}".format("cool", "Hello there!")
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
Python 3.6 and newer have literal string interpolation using f-strings:
name='world'
print(f"Hello {name}!")
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
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}."