请教各位大哥大姐,关于 print 格式化输出的问题

2016-07-01 17:18:28 +08:00
 xuweitiger

小弟在看《 Python 进阶》的时候,发现有这样一段事例代码:

def greet_me(**kwargs):

for key, value in kwargs.items():

print("{0} == {1}".format(key, value))

其中,最后一句 print 有点看不太明白,{0} == {1}是什么意思呢? 请各位大神帮忙解释一下,多谢。

2884 次点击
所在节点    Python
6 条回复
co3site
2016-07-01 17:29:11 +08:00
"{0} == {1}".format(key, value) -> str.format(key, value)
mgna17
2016-07-01 17:29:38 +08:00
就是个替换呗,这里的 {0}, {1} 分别对应 format 中的参数

format(...) method of builtins.str instance
S.format(*args, **kwargs) -> str

Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
Allianzcortex
2016-07-01 20:35:40 +08:00
等价于 print'{} == {}'.format(key,value) 比 print '%s == %s' %(key,value) 要好
cloverstd
2016-07-01 20:40:31 +08:00
其实还有 print("{key} == {value}".format(key=key, value=value))
yexiaoxing
2016-07-01 20:57:22 +08:00
linuxchild
2016-07-02 10:29:39 +08:00
大括号和双等是分开的……说起来这个执行一下不就知道了吗

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/289645

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX