Printing complex numbers

Tim Peters at
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)

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

More information about the Python-list mailing list