I am trying to implement my own class for complex numbers, to better understand how classes work in python. I have been trying to replace the str magic method to print the complex number in the a+bi format.
def __str__(self):
out="%i" % self.real
if self.imaginary==0: return out
if self.imaginary>=0: out+="+%ii" % self.imaginary
else: out+="%ii" % self.imaginary
return out
what I am interested in is the pythonic way of writing this unappealing block of code, if there is any to implement the fact that if imaginary part is negative, i should get a-bi and if imaginary part is 0 i should get a?
%-method for formatting strings. You can use thestr.formatmethod for python <3.6 and literal f-strings (as mentioned above) for python >=3.6. I can also say that single line if/else-statements are not very pythonic.:(like a normal loop, conditional statement, with statement, etc) should be multi-line