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
awker
V2EX  ›  Python

Python 字典输出问题

  •  
  •   awker · 2017-11-23 18:10:51 +08:00 · 1832 次点击
    这是一个创建于 2317 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有一个字典 d = {'a':"1",'b':"2","c":3} 有连个变量 foo='test1' bar='test2' 如何格式化输出成下面的格式?

    # str 是固定的字符
    str,id=test1,ip=test2 a=1 b =2 c=3
    3 条回复    2017-11-27 11:33:00 +08:00
    ballshapesdsd
        1
    ballshapesdsd  
       2017-11-23 18:22:08 +08:00   ❤️ 1
    ' '.join(str(i[0])+'='+str(i[1]) for i in d.items())
    jxie0755
        2
    jxie0755  
       2017-11-27 11:31:20 +08:00   ❤️ 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  
       2017-11-27 11:33:00 +08:00   ❤️ 1
    打错了,是 f-string
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3046 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:49 · PVG 20:49 · LAX 05:49 · JFK 08:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.