float to string conversion

Alex Martelli aleaxit at yahoo.com
Mon Dec 18 21:09:21 CET 2000


<deragon at 8d.com> wrote in message news:91lmt3$4b8$1 at nnrp1.deja.com...
> Greetings.
>
>
>   I am embarrassed to ask this since it is trivial, but
>   I cannot figure out how to convert a float to a string (obviously,
>   I am new to python).  Somehow, I could not find in the 2.0
>   documentation the syntax to perform the operation.

To convert 'anything' to string, you can apply the str() built-in
function:


>   The following in my function:
>
>     return MSISDN + " check FAILED:  $" + balance + errormsg

return MSISDN + " check FAILED:  $" + str(balance) + errormsg


But you also have alternatives!  The % operator, with a string
as its left operand, does a 'format' -- using format-characters
modeled on C (sorry, I don't know where to find documentation
of what Python does that doesn't depend on docs for C's own
printf!).

return "%s check FAILED: $%s %s" % (
    MSISDN, balance, errormsg)

this is one equivalent alternative to the above, as, at each
place, it's using the '%s' format, which indicates transforming
to string.  But you can make it better, since you can use a
more specialized '%f' fixed-point format and specify two
decimals...:

return "%s check FAILED: $%.2f %s" % (
    MSISDN, balance, errormsg)

this may give, e.g., '$7.00', which is more likely to be the
format you desire than 'whatever string happens'.


Alex






More information about the Python-list mailing list