Skip to main content
 首页 » 编程设计

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

2025年05月04日20飞鱼

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

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

请您参考如下方法:

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

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