推荐学习书目
› 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 · Jul 1, 2016 · 3951 views
    This topic created in 3740 days ago, the information mentioned may be changed or developed.

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

    def greet_me(**kwargs):

    for key, value in kwargs.items():

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

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

    6 replies  •  2016-07-02 10:29:39 +08:00
    co3site
        1
    co3site  
       Jul 1, 2016
    "{0} == {1}".format(key, value) -> str.format(key, value)
    mgna17
        2
    mgna17  
       Jul 1, 2016
    就是个替换呗,这里的 {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  
       Jul 1, 2016
    等价于 print'{} == {}'.format(key,value) 比 print '%s == %s' %(key,value) 要好
    cloverstd
        4
    cloverstd  
       Jul 1, 2016
    其实还有 print("{key} == {value}".format(key=key, value=value))
    yexiaoxing
        5
    yexiaoxing  
       Jul 1, 2016 via iPad   ❤️ 1
    linuxchild
        6
    linuxchild  
       Jul 2, 2016 via Android
    大括号和双等是分开的……说起来这个执行一下不就知道了吗
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4999 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 08:37 · PVG 16:37 · LAX 01:37 · JFK 04:37
    ♥ Do have faith in what you're doing.