Is there a Python equivalent to Ruby's string interpolation?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping
--
Chapters
00:00 Question
00:24 Accepted answer (Score 436)
01:45 Answer 2 (Score 150)
01:59 Answer 3 (Score 32)
02:25 Answer 4 (Score 29)
02:52 Thank you
--
Full question
https://stackoverflow.com/questions/4450...
Accepted answer links:
[literal string interpolation]: https://www.python.org/dev/peps/pep-0498/
[string interpolation]: http://docs.python.org/library/stdtypes....
[string.Template]: http://docs.python.org/library/string.ht...
Answer 3 links:
[interpy]: https://github.com/SyrusAkbary/interpy
Answer 4 links:
http://docs.python.org/library/functions...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #stringinterpolation #languagecomparisons
#avk47
ACCEPTED ANSWER
Score 437
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"))
ANSWER 2
Score 152
Since Python 2.6.X you might want to use:
"my {0} string: {1}".format("cool", "Hello there!")
ANSWER 3
Score 32
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}."
ANSWER 4
Score 29
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