Bo Peng wrote: > 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' Floats make a distinction betwen repr and str: repr(x) uses 17 significant digits (to ensure that repr(1.0) and repr(1.0+epsilon) are distinct, while str(x) uses only 12 (to produce more user-friendly output). For lists, repr(x) calls repr(x[i]) for each of its elements. Just what you'd expect. But lists, unlike floats, do *not* make a distinction between str and repr; i.e. str(x) == repr(x). The main reason for doing it this way was to avoid confusion in cases like str(["1, 2", 3]): If list.__str__ were implemented like the list_str function below, the result would look like a list of 3 ints instead of a string and an int. The unfortunate side effect of this is to make str(list of floats) ugly, but... > Is there any way to fix this, other than checking the type of everything > and output with %.4f? def list_str(x): return '[%s]' % ', '.join(map(str, x)) -- http://mail.python.org/mailman/listinfo/python-list