Ruby example:
name = \"Spongebob Squarepants\"
puts \"Who lives in a Pineapple under the sea? \\n#{name}.\"
The successful Python string co
import inspect
def s(template, **kwargs):
"Usage: s(string, **locals())"
if not kwargs:
frame = inspect.currentframe()
try:
kwargs = frame.f_back.f_locals
finally:
del frame
if not kwargs:
kwargs = globals()
return template.format(**kwargs)
Usage:
a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found
PS: performance may be a problem. This is useful for local scripts, not for production logs.
Duplicated:
Python string formatting: % vs. .format
What is the Python equivalent of embedding an expression in a string? (ie. "#{expr}" in Ruby)
What is Ruby equivalent of Python's `s= "hello, %s. Where is %s?" % ("John","Mary")`
Is there a Python equivalent to Ruby's string interpolation?
String interpolation is going to be included with Python 3.6 as specified in PEP 498. You will be able to do this:
name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')
Note that I hate Spongebob, so writing this was slightly painful. :)
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"))