[英]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
我以為是因為其他括號沒有顯示期望的變量類型,但是我無法弄清楚指定字符串的字符是什么。
將{0:02d}
更改為{:02d}
。
冒號前面的零告訴您使用format
的第一個參數(在您的示例中為baseurl
)。 錯誤消息告訴您,它不能從自動填充字段切換為按索引執行。 您可以在文檔中閱讀有關格式字符串語法的更多信息。
這應該工作
url = '{}?action={}&functionId={}&yearMonth={}{num:02d}'.format(baseurl, action, funcId, year, num=month)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.