Printing complex numbers

Tim Peters tim.one at home.com
Sat Dec 15 13:57:19 EST 2001


[Stephen Boulet]
> I know that for floats you can do:
>
> print '.3f' % x
>
> or
>
> print '.3e' % x

You need "%" signs in there.

> But how do you do the same for complex numbers?

There isn't a special format code for complex; so print x.real and x.imag
separately, e.g.

>>> x = 12.5+3.24j
>>> print "%.3f%+.3fj" % (x.real, x.imag)
12.500+3.240j
>>>

If you want "the usual" str() or repr() form of a complex number, just use
%s or %r (respectively) in the format.

>>> print "%s" % x
(12.5+3.24j)
>>>





More information about the Python-list mailing list