【问题标题】:format a string using a string and (padded) number使用字符串和(填充)数字格式化字符串
【发布时间】:2018-01-06 02:04:25
【问题描述】:

我正在为一个 http 请求组装一个 url

baseurl = 'http://..'
action = 'mef'
funcId = 100
year = 2018
month = 1

url = '{}?action={}&functionId={}&yearMonth={}{}'.format(baseurl, action, funcId, year, month)

困扰我的是,如果月份数小于 10,我需要用 0 填充。 如果它是唯一要格式化的变量,我知道如何填充数字:

'{0:02d}'.format(month)  # returns: 01

虽然当我尝试这个时:

'{}?action={}&functionId={}&yearMonth={}{0:02d}'.format(baseurl, action, funcId, year, month)

导致错误:

ValueError: cannot switch from automatic field numbering to manual field specification

我认为这是因为其他括号没有显示预期的变量类型,但我无法弄清楚用什么字符来指定字符串。

【问题讨论】:

  • 我想要完整的回溯。

标签: python string-formatting


【解决方案1】:

{0:02d} 更改为{:02d}

冒号前面的零表示使用format 的第一个参数(在您的示例中为baseurl)。错误消息告诉您它无法从自动填写字段切换到按索引执行。您可以在Format String Syntax 的文档中阅读有关此主题的更多信息

【讨论】:

  • 这也是一个不错的解决方案。我确实通过了您链接到的那个表,我无法理解如何将它实现到我的代码中。我遇到了这篇文章(stackoverflow.com/questions/10875121/…),但它使用了不同的格式。无论如何,通过这两种解决方案,我对格式化应该如何工作有了更好的理解。谢谢!
【解决方案2】:

这个应该可以的

url = '{}?action={}&functionId={}&yearMonth={}{num:02d}'.format(baseurl, action, funcId, year, num=month)

https://www.python.org/dev/peps/pep-3101/

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 2017-06-26
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多