Search code examples
pythonlistdecimalpretty-print

Print tuple of Decimals without the label "Decimal"


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)

Solution

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