Print tuple of Decimals without the label "Decimal"

928 views Asked by At

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)
2

There are 2 answers

1
Mike Müller On BEST ANSWER

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)
2
Netwave On

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))