1

This next behaviour befuddles me, any explanation would be appreciated.

>>> a = (0.1457164443693023, False)
>>> print a
(0.1457164443693023, False)
>>> print a[0]
0.145716444369

Using python 2.7

Eran
  • 2,324
  • 3
  • 22
  • 27
  • 2
    That's not really the same question, there it's two different numbers, here it is on and the same. Also in my case both times it is printed and not converted to and from string and float. – Eran Aug 04 '13 at 06:39
  • 1
    `print x` is basically equivalent to `sys.stdout.write(str(x))`. When you do `str()` on a tuple, the elements of the tuple are returned as their `repr`. If they used `str`, it would be confusing to get `(1,)` for both `print ('1',)` and `print (1,)`. – Alok Singhal Aug 04 '13 at 06:47
  • 1
    FYI, this behavior is changed in Python 3 where the *str* and *repr* are both at full precision. – Raymond Hettinger Aug 04 '13 at 07:07

3 Answers3

7

The only difference is the print. The number doesn't change, just its representation. You can reduce your problem to:

>>> 0.1457164443693023
0.1457164443693023
>>> print 0.1457164443693023
0.145716444369

(I guess (and this is only and merely a guess) this boils down to __repr__ vs __str__ or something along this line)

user2357112
  • 260,549
  • 28
  • 431
  • 505
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
  • hmm, it is indeed that in this case a[0].__str__() gives the shorter number and a[0].__repr__() give the longer one. I guess printing a float uses str while printing a tupple uses repr. Thanks. – Eran Aug 04 '13 at 06:44
  • 2
    @Eran print on a tuple also uses `str()`, but `str()` is called on the tuple. A tuple's string representation uses `repr()` on the elements of the tuple itself. – Alok Singhal Aug 04 '13 at 06:49
6

The first calls __ repr __ , the second __ str __

a = (0.1457164443693023, False)
print a
>>> (0.1457164443693023, False)
print a[0]
>>> 0.145716444369

print repr(a[0])
>>> 0.1457164443693023
print str(a[0])
>>> 0.145716444369

For some design reason Double.__ str __() returns fewer decimals.

Akinakes
  • 657
  • 4
  • 10
3

Looks like python does not print the full accuracy of a float, but it is still there.

>>> a = (0.1457164443693023, False)

>>> print a
(0.1457164443693023, False)

>>> print repr(a[0])
0.1457164443693023
Afiefh
  • 920
  • 1
  • 7
  • 15