-1

I have a Vector class as follows:

class Vector(object):

    def __init__(self, coordinates):
        self.coordinates = tuple([Decimal(x) for x in coordinates])

    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

If I run the code below...

v1 = Vector([1,1])
print v1

...I get

Vector: (Decimal('1'), Decimal('1'))

How can I get rid of the label 'Decimal'? The output should look like:

Vector: (1, 1)
martineau
  • 119,623
  • 25
  • 170
  • 301
Thomas Grusz
  • 53
  • 1
  • 1
  • 7
  • 1
    Possible duplicate of [Python Decimal to String](http://stackoverflow.com/questions/11093021/python-decimal-to-string) – Mureinik Dec 23 '16 at 10:43
  • I was aware of the str() method, but simply applying it to the tuple did not remove the label 'Decimal'. The combination of the str() and join() methods inside a list comprehension solved my problem. – Thomas Grusz Dec 23 '16 at 11:44

2 Answers2

2

Just call the str function:

import decimal
d = decimal.Decimal(10)
d
Decimal('10')
str(d)
'10'

For your code:

def __str__(self):
    return 'Vector: {}'.format(map(str, self.coordinates))
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 5
    Never call double-underscore methods directly. This code should be `str(d)`. – Daniel Roseman Dec 23 '16 at 10:41
  • That's not quite the output that the OP wants: it has square brackets instead of round ones, and it has unwanted quote marks around the co-ords. And in Python 3 `map` returns a map object, not a list, so the output will be even more inscrutable. – PM 2Ring Dec 23 '16 at 10:57
2

Adding str() around your decimals works:

from __future__ import print_function
from decimal import Decimal

class Vector(object):

    def __init__(self, coordinates):
        self.coordinates = tuple([Decimal(x) for x in coordinates])

    def __str__(self):
        return 'Vector: ({})'.format(', '.join(str(x) for x in self.coordinates))

v1 = Vector([1,1])
print(v1)

Output:

Vector: (1, 1)
Mike Müller
  • 82,630
  • 20
  • 166
  • 161