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

请教一个问题: 关于 format 的基础问题

  •  
  •   foxyier · Oct 9, 2018 · 2819 views
    This topic created in 2947 days ago, the information mentioned may be changed or developed.

    现有这么一个小需求, 求助一下: news = "{'1': 1, '2': 2}, {name}" 能否通过 format 只将{name}格式化成 Amy

    7 replies  •  2018-10-12 15:21:17 +08:00
    qiang223
    qiang223
    Oct 9, 2018
    1
    可以室友格式替换符
    "{'1': 1, '2': 2}, {%s}" % ('Amy')
    foxyier
    foxyier
    OP
    Oct 9, 2018
    2
    @qiang223 我想用 format 实现, 不然的话, 如果是这样的字符串呢? "{'1': 1, '2': 2, '3': '%s'}, {name}"
    0ZXYDDu796nVCFxq
    0ZXYDDu796nVCFxq
    Oct 9, 2018 via Android
    3
    "{{'1':1,'2':2}}, {name}".format(name='Amy')
    insomnia1232
    insomnia1232
    Oct 9, 2018
    4
    split()大括号,结果里没有引号的就是 name
    foxyier
    foxyier
    OP
    Oct 9, 2018
    5
    @gstqc 了解了, 多谢
    yim7
    yim7
    Oct 11, 2018
    6
    In [6]: def myformat(str,name):
    ...: return str.replace('{name}',name)
    ...:
    ...:

    In [7]: myformat("{'1': 1, '2': 2}, {name}", 'Amy')
    Out[7]: "{'1': 1, '2': 2}, Amy"
    foxyier
    foxyier
    OP
    Oct 12, 2018
    7
    @yim7 我就是这么做的, 只是想了解一下 format 能不能做。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5015 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 53ms · UTC 09:08 · PVG 17:08 · LAX 01:08 · JFK 04:08
    ♥ Do have faith in what you're doing.