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
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())
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.