Reputation: 5945
I would like to print variables values in python. e.g:
a=3
b=5
print 'blah blah: a = {a}, b = {b}'.format(a=a, b=b)
result is:
blah blah: a = 3, b = 5
My question is how to do it in a short elegant and readable manner.
e.g., is there a way to write something like (pseudo code below)
print 'blah blah: {a}, {b}'.format(a,b)
to get the same result?
Thanks! (BTW: i am using python 2.7)
EDIT (clarification): For logging purpose, sometimes i have many variables that i would like to print, so i prefer not doing something like
print 'a={}, b={}, c={},...'.format(a,b,c...)
because it is a source for bugs (i.e. I just want to specify the varaible name in the string itself and not care about the order of the variables).
e.g., ultimatly, something that looks like
print 'blah blah: {a}, {b}, {c}, {d}, {e}, {f}'.format(c,e,a,f,d,b)
with a result like:
blah blah: a=3, b=5, c=7, d=22, e=2, f=532
Upvotes: 0
Views: 417
Reputation: 133929
import inspect
class fdict(dict):
def __init__(self, dct):
for k, v in dct.items():
self[k] = "{} = {}".format(k, v)
def flocals():
frame = inspect.currentframe()
return fdict(frame.f_back.f_locals)
def localformat(string):
frame = inspect.currentframe()
dct = fdict(frame.f_back.f_locals)
return string.format(**dct)
Then import localformat
anywhere you want and use this:
>>> a = 5
>>> b = 6
print(localformat('{a}, {b}'))
or call the flocals()
to get a string to pass to format.
Upvotes: 0
Reputation: 654
You can use your second approach with **locals()
instead of a, b
. locals()
returns a dict containing all local variables. **
unpacks it so you can use it in function calls (function(**{'a': 3, 'b': 4, 'c': 14})
is the same as function(a=3, b=4, c=14)
)
>>> a = 3
>>> b = 4
>>> c = 14
>>> print 'a = {a}, b = {b}'.format(**locals())
a = 3, b = 4
To avoid 'a = {a}'
you can do something like
print '{a}, {b}'.format(**{k:'{} = {}'.format(k,v) for (k,v) in locals().iteritems()})
Upvotes: 3
Reputation: 53688
If you know the order that a
and b
will be in, you don't need to pass them as named arguments in your formatting:
a = 3
b = 5
print('blah blah: a = {}, b = {}'.format(a, b))
Alternatively you could store your variables in a dictionary as below and then use **kwargs
unpacking when passing the dict to format.
d = dict(a=3, b=5)
print('blah blah: a = {a}, b = {a}'.format(**d))
Upvotes: 1