1

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.

Dutchman
  • 67
  • 10

2 Answers2

4

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

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • Thats a nice solution too. I did pass that table you're linking to, I couldn't make much sense of it to understand how to implement it into my code. I came across this post ( https://stackoverflow.com/questions/10875121/using-format-to-format-a-list-with-field-width-arguments#10875142 ), but that made a different use of formatting. Anyway, with both solutions I'm getting a better understanding of how formatting is supposed to work. Thanks! – Dutchman Jan 06 '18 at 02:32
3

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/

Axalix
  • 2,831
  • 1
  • 20
  • 37