3
votes

While writing a module in Python 2.7 I had the need of a way for doing

name = "Rodrigo"
age = 34
print f"Hello {name}, your age is {age}".format()

although I know I could just do:

print "Hello {name}, your age is {age}".format(name=name, age=age)

format() would look in the scope for variables name and age, cast them to a string (if possible) and paste into the message. I've found that this is already implemented in Python 3.6+, called Formatted String Literals. So, I was wondering (couldn't find it googling) if anyone has made an approach to something similar for Python 2.7

2
AFAIK, this is still a Python 3.6 and greater feature only. - Christian Dean
A rather hacky version is to use .format(dict(globals(), **locals())) - Jon Clements♦

2 Answers

7
votes

You can try the hackish way of doing things by combining the builtin locals function and the format method on the string:

foo = "asd"
bar = "ghi"

print("{foo} and {bar}".format(**locals())
3
votes

Here's an implementation that automatically inserts variables. Note that it doesn't support any of the fancier features python 3 f-strings have (like attribute access):

import inspect

def fformat(string):
    caller_frame = inspect.currentframe().f_back
    names = dict(caller_frame.f_globals, **caller_frame.f_locals)
    del caller_frame
    return string.format(**names)
a = 1
foo = 'bar'
print fformat('hello {a} {foo}')
# output: "hello 1 bar"