V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
xuweitiger
V2EX  ›  Python

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

  •  
  •   xuweitiger · 2016-07-01 17:18:28 +08:00 · 2855 次点击
    这是一个创建于 2827 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    def greet_me(**kwargs):

    for key, value in kwargs.items():

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

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

    6 条回复    2016-07-02 10:29:39 +08:00
    co3site
        1
    co3site  
       2016-07-01 17:29:11 +08:00
    "{0} == {1}".format(key, value) -> str.format(key, value)
    mgna17
        2
    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
        3
    Allianzcortex  
       2016-07-01 20:35:40 +08:00
    等价于 print'{} == {}'.format(key,value) 比 print '%s == %s' %(key,value) 要好
    cloverstd
        4
    cloverstd  
       2016-07-01 20:40:31 +08:00
    其实还有 print("{key} == {value}".format(key=key, value=value))
    yexiaoxing
        5
    yexiaoxing  
       2016-07-01 20:57:22 +08:00 via iPad   ❤️ 1
    linuxchild
        6
    linuxchild  
       2016-07-02 10:29:39 +08:00 via Android
    大括号和双等是分开的……说起来这个执行一下不就知道了吗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   948 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:02 · PVG 05:02 · LAX 14:02 · JFK 17:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.