Formatting numbers with leading zeros

S

Stian

Hi, I'm sort of new to Python and I've just discovered the amazing
formatting using the % operator. One thing I can't figure out is how
to format numbers so that they get leading zeros, for example I want
the output 1x01 instead of 1x1 (used in naming my avi files of shows).
I've used this so far:

print '%sx%s'%(season,episode)

which gives the output 1x1, but I want 1x01 =p Any way to format it
using the % method?
 
F

Fredrik Lundh

Stian said:
Hi, I'm sort of new to Python and I've just discovered the amazing
formatting using the % operator. One thing I can't figure out is how
to format numbers so that they get leading zeros, for example I want
the output 1x01 instead of 1x1 (used in naming my avi files of shows).
I've used this so far:

print '%sx%s'%(season,episode)

which gives the output 1x1, but I want 1x01 =p Any way to format it
using the % method?

assuming that season and episode are integers:

print "%dx%02d" % (season, episode)

(if not, use int() to convert from strings to integers)

more info here:

http://docs.python.org/lib/typesseq-strings.html

</F>
 
T

Thomas D'Tak

One thing I can't figure out is how
to format numbers so that they get leading zeros

... ... ...

print '%sx%s'%(season,episode)

which gives the output 1x1, but I want 1x01

I think you are looking for the string method zfill();
you can find it here in Python's Library Reference:

http://www.python.org/doc/2.3.4/lib/string-methods.html

If e.g. episode = '1', episode.zfill(2) will return '01'
and episode.zfill(3) will return '001' etc. etc.

HTH, Th.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top