0

Is it possible to remove parentheses when is printed a complex number in pytthon?. I would like to print several complex numbers in python, for example as;

for i in range(100):
    n=i+1j
    print(n)

but in this case any complex number is printed as (i+1j), could I remove theses parentheses?. Any help is welcome. Thanks.

Don P.
  • 25
  • 3
  • 1
    This may help: [Formatting Complex Numbers](https://stackoverflow.com/questions/7746143/formatting-complex-numbers) – sj95126 Aug 01 '22 at 22:35
  • You could either create a type that implements a different `__str__` and `__repr__`, but you should probably just format while printing, as @sj95126 suggests. – Grismar Aug 01 '22 at 22:37
  • You can also quickly access the real and imaginary components of the complex type via `n.real` and `n.imag` respectively which is useful for formatting when printing – Reece Aug 01 '22 at 22:38

1 Answers1

1

The n object defines a __str__ method which is called when print tries to convert it to a string. You can access the parts individually if you need to print them differently. For example, to print just the real, then just the imaginary part:

for i in range(100):
    n = i + 1j
    print(n.real, n.imag)

This output gives:

0.0 1.0
1.0 1.0
2.0 1.0
3.0 1.0
...

So the real and imaginary parts are being interpreted as float now instead of complex, but you still have the trailing .0 which you might not want. If you know everything is an int, you can change the formatting:

for i in range(100):
    n = i + 1j
    print(int(n.real), int(n.imag))

Or, you can ask python to guess what the best format will be:

for i in range(100):
    n = i + 1j
    print(f"{n.real:g}", f"{n.imag:g}")
SNygard
  • 916
  • 1
  • 9
  • 21