Formatting numbers with leading zeros

Fredrik Lundh fredrik at pythonware.com
Sun Sep 19 16:18:59 EDT 2004


"Stian" wrote:

> 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> 






More information about the Python-list mailing list