使用字符串和(填充的)数字格式化字符串

format a string using a string and (padded) number

我正在为 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

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

这个应该有用

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

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

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

冒号前的零告诉我们使用 format 的第一个参数(在您的示例中为 baseurl)。错误消息告诉您它无法从自动填写字段切换到按索引完成。您可以在 Format String Syntax

的文档中阅读有关此主题的更多信息