Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatted String Literals in Python 2

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

like image 383
Rodrigo E. Principe Avatar asked Dec 06 '25 03:12

Rodrigo E. Principe


2 Answers

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())
like image 62
omu_negru Avatar answered Dec 07 '25 19:12

omu_negru


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"
like image 28
Aran-Fey Avatar answered Dec 07 '25 17:12

Aran-Fey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!