Reputation: 57
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.
Upvotes: 0
Views: 66
Reputation: 60974
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
Upvotes: 3
Reputation: 2871
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/
Upvotes: 2