[Tutor] turning a number into a formated string

Ertl, John john.ertl at fnmoc.navy.mil
Wed Dec 15 22:25:46 CET 2004


Very elegant, It makes me feel like "I should have thought of that".  Thanks
for the help and the reminder to think of the simplistic approach.

John 

-----Original Message-----
From: Tim Peters [mailto:tim.peters at gmail.com]
Sent: Wednesday, December 15, 2004 12:15
To: Ertl, John
Cc: tutor-list (Python)
Subject: Re: [Tutor] turning a number into a formated string

[Ertl, John]
> I need to take a number and turn it into a formatted string.
> The final output needs to look like  XXXXYYYY  when the X is the
> integer part padded on the left and  Y is the decimal part padded
> on the right.
> I figured I could split the number at "." and then use zfill or
> something like this  (LEVEL1 = "%04d" % LEVEL1) for the XXXX
> part but I am not sure how to right pad the decimal part of the
> number.
> Example.
> 1 and 1.0  needs to look like 00010000 ( I figured I would have to
> check the length of the list made from the split to see if a decimal
> portion existed)
> 1.1 needs to look like 00011000
> 22.33 needs to look like 00223330

Really?  The input has two digits 3, but the output has three digits
3.  I'll assume you meant 00223300 instead.

> 4444.22 needs to look like 44442200
> Any ideas on the right padding the decimal side using "0"

I expect that a "%09.4f" format does everything you asked for, except
that it contains a period.  So let's try to repair that:

>>> def johnpad(n):
...     return ("%09.4f" % n).replace('.', '')

Then:

>>> johnpad(1)
'00010000'
>>> johnpad(1.0)
'00010000'
>>> johnpad(1.1)
'00011000'
>>> johnpad(22.33)
'00223300'
>>> johnpad(4444.22)
'44442200'
>>>


More information about the Tutor mailing list