0

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.

1
  • I would like the full traceback. Commented Jan 6, 2018 at 2:08

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 ( stackoverflow.com/questions/10875121/… ), 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!
2

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.