[Tutor] puzzled by Python 3's print()

Evert Rol evert.rol at gmail.com
Thu Jul 1 10:45:31 CEST 2010


>>>> x = 2000000000000034
>>>> x/2
> 1000000000000017.0
>>>> print(x/2)
> 1e+15
> 
> I was expecting, in fact needing, 1000000000000000017 or 1000000000000000017.0
> 
> 1e+15 is unsatisfactory. Am I forced to use the decimal module?

Can't you use string formatting? Eg:
>>> print("{0:15.0f}".format(x/2))
1000000000000017


print uses __str__()/str(), which I assume was deemed unsatisfactory in Python 2: it's supposed to show a 'simple, nice' representation of anything, while __repr__() (or the repr() function) shows a more exact representation (or rather, repr() shows an object that can be used to recreate a new identical object: float(repr(x/2)) gives back the correct float, while float(str(x/2)) wouldn't). 
So they've apparently changed __str__() to make things somewhat more readable. __repr__()/repr() is what you get with just using x/2 on the command line:

>>> x/2
1000000000000017.0
>>> repr(x/2)
1000000000000017.0


And you could actually use:

>>> print(repr(x/2))
1000000000000017.0


I would go for the format statement, though. But that may depend on your precise needs.



More information about the Tutor mailing list