如何正确打印输出__str__

时间:2019-12-09 10:19:57

标签: python string

如何正确打印输出 str

class Complex(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary

    def __add__(self, other):
        return Complex(self.real+other.real, self.imaginary+other.imaginary)

    def __sub__(self, other):
        return Complex(self.real-other.real, self.imaginary-other.imaginary)

    def __str__(self):
        return '{} & {}i'.format(self.real, self.imaginary)
if __name__ == '__main__':
    c = map(float, input().split())
    d = map(float, input().split())
    x = Complex(*c)
    #print (x)
    y = Complex(*d)
    #print (y)
    print(*map(str, [x+y, x-y]), sep='\n')

输入

2 1 5 6

输出

7.0 & 7.0i -3.0 & -5.0i

如果要加法,应该打印+,对于减法,应该打印-

7.00+7.00i -3.00-5.00i

3 个答案:

答案 0 :(得分:1)

在您的 str 实现中使用它。

def __str__(self):
        return f"{self.real}{ '+' if self.imaginary >= 0 else ''}{self.imaginary}i"

答案 1 :(得分:1)

代替此:

def __str__(self):
        return '{} & {}i'.format(self.real, self.imaginary)

您可以这样做:

def __str__(self):
    def __map_imaginary(imag):
        if imag > 0:
            return "+{:2f}i".format(imag)
        if imag < 0:
            return "{:2f}i".format(imag)
        if imag == 0:
            return ""
    return "{}{}".format(self.real, __map_imaginary(self.imag))

我假设您不希望打印等于0的虚部。您可以随意更改。

答案 2 :(得分:1)

class Complex(object):
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary

    def __add__(self, other):
        return Complex(self.real+other.real, self.imaginary+other.imaginary)

    def __sub__(self, other):
        return Complex(self.real-other.real, self.imaginary-other.imaginary)

    def __str__(self):
        return '{:.2f}{}{:.2f}i'.format(self.real, '+' if self.imaginary >= 0 else '', self.imaginary)
if __name__ == '__main__':
    c = map(float, input().split())
    d = map(float, input().split())
    x = Complex(*c)
    #print (x)
    y = Complex(*d)
    #print (y)
    print(*map(str, [x+y, x-y]), sep='\n')
  1. 如果var为正数,则应手动添加符号。
  2. 在您的预期结果中,您还有2个小数点,因此您需要添加{:.2f}