control precision for str(obj) output?

Mike Meyer mwm at mired.org
Tue May 3 22:32:54 EDT 2005


Bo Peng <bpeng at rice.edu> writes:

> Dear list,
>
> I have enjoyed the convenience to output any object with str(obj) for
> a while. However, I get long output for things like str([0.0002]) in
> my output (which bothers my users more than me though). I also do not
> understand why the following is happening:
>
>  >>> str([0.0002])
> '[0.00020000000000000001]'
>  >>> str(0.0002)
> '0.0002'
>
> Is there any way to fix this, other than checking the type of
> everything and output with %.4f?

Two things are going on here.

1) str is returning a "nicely printable" version of the object. For
floats, that means providing a precision so they behave as naive users
expect. repr, on the other hand, is returning a printable
representation of the object - which in the case of floats means the
true value of the float, not it's "nice" approximation.

2) str on a list uses repr to turn all the elements in the list to
strings for printing. This is pretty much required for strings to be
recognizable as such in the output.

And no, there's no way to control what repr is going to do. You could
subclass list and provide an str method that checks for floats, and
calls str on them instead of repr (probably better than using %.4f on
them all), but you can't really fix list.

Someone want to tell me the procedure for submitting FAQ entries, so I
can do that for this?

    Thanks,
    <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list