简体   繁体   中英

format a string using a string and (padded) number

I'm assembling a url for an http request

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

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

What's bugging me is I need the month number to be padded with a 0 if its less than 10. I know how to pad a number if its the only variable to format:

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

Though when I try this in:

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

It results in the error:

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

I assumed it's because the other brackets aren't shown what type of variable to expect, but I cant figure out with what character to specify a string.

Change {0:02d} to {:02d} .

The zero preceding the colon is telling to use the first argument of format ( baseurl in your example). The error message is telling you that it can't switch from automatically filling in the fields to doing it by index. You can read more on this subject at the docs for Format String Syntax

This one should work

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM