2

Please put me out of my misery. The following example seems to be using y twice rather than y and then m.

>>> m=8 >>> y=11 >>> print '20{0:02d}{0:02d}01'.format(y, m) 20111101 

I've been through as much of the documentation as I can but can't figure out what would have been relatively straightforward with the old procedure:

>>> print '20%02d%02d01' % ( y, m ) 20110801 

If someone could explain where I'm going wrong I'd be really grateful.

2
  • 1
    '20{0:02d}{0:02d}01' should be '20{0:02d}{1:02d}01' Commented May 7, 2012 at 16:25
  • 2
    Even simpler: '20{:02d}{:02d}01' Commented May 7, 2012 at 17:14

2 Answers 2

6

This will do what you want:

print '20{0:02d}{1:02d}01'.format(y, m) 

You referred to the first argument twice.

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

2 Comments

Doh! Thanks. I read the Python docs over and over but still missed this.
You could leave out the 0 and 1 indexes (keep the colons though). You only need them if you want to reuse the args multiple times or if you want to reorder them.
3
>>> print '20{0:02d}{1:02d}01'.format(y, m) 

you need to use the next arg in the arg list.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.