打印没有标签的小数组元素"十进制"

时间:2016-12-23 10:38:12

标签: python list decimal pretty-print

我有一个Vector课程如下:

class Vector(object):

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

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

如果我运行以下代码......

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

......我得到了

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

如何摆脱标签'十进制'? 输出应如下所示:

Vector: (1, 1)

2 个答案:

答案 0 :(得分:1)

只需拨打str功能:

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

代码:

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

答案 1 :(得分:1)

在小数点周围添加str()

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)

输出:

Vector: (1, 1)