简体   繁体   English

在python中打印变量值。 有什么优雅的格式可以做到吗?

[英]printing variables values in python. Is there any elegant formatting to do it?

I would like to print variables values in python. 我想在python中打印变量值。 eg: 例如:

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. 我的问题是如何以简短且易读的方式进行操作。

eg, 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) (顺便说一句:我正在使用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 (ie I just want to specify the varaible name in the string itself and not care about the order of the variables). 因为它是bug的来源(即,我只想在字符串本身中指定可变名称,而不在乎变量的顺序)。

eg, 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

You can use your second approach with **locals() instead of a, b . 您可以对**locals()而不是a, b使用第二种方法。 locals() returns a dict containing all local variables. locals()返回包含所有局部变量的字典。 ** 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) ) **解压缩它,以便您可以在函数调用中使用它( function(**{'a': 3, 'b': 4, 'c': 14})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 为了避免'a = {a}'您可以执行以下操作

print '{a}, {b}'.format(**{k:'{} = {}'.format(k,v) for (k,v) in locals().iteritems()})

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: 如果知道ab的顺序,则不需要在格式中将它们作为命名参数传递:

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. 或者,您可以将变量存储在如下的字典中,然后在将字典传递给格式时使用**kwargs解包。

d = dict(a=3, b=5)

print('blah blah: a = {a}, b = {a}'.format(**d))
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: 然后在任何需要的地方导入localformat并使用它:

>>> a = 5
>>> b = 6
print(localformat('{a}, {b}'))

or call the flocals() to get a string to pass to format. 或调用flocals()获取要传递给格式的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM