最近有人告诉我,我们可以在Python中打印变量,就像Perl一样.
代替:
print("%s, %s, %s" % (foo, bar, baz))
Run Code Online (Sandbox Code Playgroud)
我们可以这样做:
print("%(foo)s, %(bar)s, %(baz)s" % locals())
Run Code Online (Sandbox Code Playgroud)
像在Perl中那样,在Python中打印变量的方式是不是很简单?我认为第二个解决方案实际上看起来非常好并且使代码更具可读性,但是那里的locals()让它看起来像是一种令人费解的方式.
jat*_*ism 10
唯一的另一种方法是使用Python 2.6 +/3.x .format()方法进行字符串格式化:
# dict must be passed by reference to .format()
print("{foo}, {bar}, {baz}").format(**locals())
Run Code Online (Sandbox Code Playgroud)
或者按名称引用特定变量:
# Python 2.6
print("{0}, {1}, {2}").format(foo, bar, baz)
# Python 2.7/3.1+
print("{}, {}, {}").format(foo, bar, baz)
Run Code Online (Sandbox Code Playgroud)
使用% locals()或.format(**locals())不总是一个好主意.例如,如果从本地化数据库中提取字符串或者可能包含用户输入,则可能存在安全风险,并且它会混合程序逻辑和转换,因为您必须处理程序中使用的字符串.
一个好的解决方法是限制可用的字符串.例如,我有一个程序可以保存有关文件的一些信息.所有数据实体都有这样的字典:
myfile.info = {'name': "My Verbose File Name",
'source': "My Verbose File Source" }
Run Code Online (Sandbox Code Playgroud)
然后,当文件是进程时,我可以这样做:
for current_file in files:
print 'Processing "{name}" (from: {source}) ...'.format(**currentfile.info)
# ...
Run Code Online (Sandbox Code Playgroud)