推荐学习书目
› 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
awker
V2EX  ›  Python

Python 字典输出问题

  •  
  •   awker · Nov 23, 2017 · 2773 views
    This topic created in 3230 days ago, the information mentioned may be changed or developed.
    有一个字典 d = {'a':"1",'b':"2","c":3} 有连个变量 foo='test1' bar='test2' 如何格式化输出成下面的格式?

    # str 是固定的字符
    str,id=test1,ip=test2 a=1 b =2 c=3
    3 replies  •  2017-11-27 11:33:00 +08:00
    ballshapesdsd
        1
    ballshapesdsd  
       Nov 23, 2017   ❤️ 1
    ' '.join(str(i[0])+'='+str(i[1]) for i in d.items())
    jxie0755
        2
    jxie0755  
       Nov 27, 2017   ❤️ 1
    其实你这个关键就是怎么把字典中的值按格式 print()出来把? python3 有个新的 format 方式,叫 f=string,比较好理解:
    也就是在 一个"string"前面加一个 f,然后用花括号来带入格式
    a = 123
    b = 456
    print(f"the value of a is {a}, the value of b is {b}")
    # >>> the value of a is 123, the value of b is 456

    同理
    d = {'a':"1",'b':"2","c":3}
    print(f"a={d['a']} b={d['b']} c={d['c']}")
    合并于你的其他要求就是:
    print(f"string, id={foo} ip={bar} a={d['a']} b={d['b']} c={d['c']}")
    jxie0755
        3
    jxie0755  
       Nov 27, 2017   ❤️ 1
    打错了,是 f-string
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   849 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 19:16 · PVG 03:16 · LAX 12:16 · JFK 15:16
    ♥ Do have faith in what you're doing.