operation with strings and numbers

Carlos Ribeiro carribeiro at gmail.com
Fri Oct 15 19:46:26 CEST 2004

On Fri, 15 Oct 2004 18:35:16 +0200, Hellas <hellas_74 at hotmail.com> wrote:
> Hello guy
> I'm italian boy, I need help for doing a strange thing with numbers
> I have a number from operation like this:
> a = float("010.123")
> b = float("001.124")
> p= a*b
> p="%06.3f" % p
> the resulted is "_11,278" where "_" is a space
> I must to change the formatting of this number in "011278" but I don't known
> what to do
> Could you help me please?
> thanks a lot

There are two things that you need to do: fix the format string, and
process the string after the conversion is made. Assuming you want to
do (1), there is a very simple mistake to fix. Try this:

>>> "%07.3f" % p

Instead of "06", use "07" -- remember that you have to count the "."
in the floating point representation. After you've done that, remove
the "." from the resulting string, by replacing it with a empty

s = "%07.3f" % p
s = s.replace(".","")

If you want to do everything into a single line, then just do it:

s = ("%07.3f" % p).replace(".","")

Another option is to convert the floating point number to a integer
*before* formatting:

>>> "%06d" % int(p*1000)

Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com

More information about the Python-list mailing list