Python中不符合风格的打印变量的方法?
最近有人给我演示了,我们可以像在Perl中那样在Python中打印变量。
比如说,原本我们可以这样写:
print("%s, %s, %s" % (foo, bar, baz))
但我们也可以这样做:
print("%(foo)s, %(bar)s, %(baz)s" % locals())
有没有一种看起来不那么复杂的方式,在Python中打印变量,就像我们在Perl中那样?我觉得第二种方法看起来真的不错,让代码更容易读懂,但里面的locals()让它看起来有点复杂。
5 个回答
3
我个人比较喜欢使用 .format()
这个方法,不过你也可以用其他方式来实现:
age = 99
name = "bobby"
print name, "is", age, "years old"
这样会输出: bobby is 99 years old
。注意这里有自动加上的空格。
或者,你也可以用一些比较复杂的方法:
def p(*args):
print "".join(str(x) for x in args))
p(name, " is ", age, " years old")
5
使用 % locals()
或 .format(**locals())
并不总是个好主意。举个例子,如果字符串是从本地化数据库中提取的,或者包含用户输入,这可能会带来安全风险。此外,这样做还会把程序的逻辑和翻译混在一起,因为你需要关注程序中使用的字符串。
一个好的解决办法是限制可用的字符串。例如,我有一个程序用来保存一些关于文件的信息。所有的数据实体都有一个像这样的字典:
myfile.info = {'name': "My Verbose File Name",
'source': "My Verbose File Source" }
然后,当处理文件时,我可以这样做:
for current_file in files:
print 'Processing "{name}" (from: {source}) ...'.format(**currentfile.info)
# ...
10
另一种方法是使用 Python 2.6 及以上版本或者 3.x 版本中的 .format()
方法来格式化字符串:
# dict must be passed by reference to .format()
print("{foo}, {bar}, {baz}").format(**locals())
或者可以通过变量的名字来引用特定的变量:
# Python 2.6
print("{0}, {1}, {2}").format(foo, bar, baz)
# Python 2.7/3.1+
print("{}, {}, {}").format(foo, bar, baz)