Python complex numbers printing?

i can print 2 python vars like this

||print (’ dv1 = ’ , dv1 )|

||print (’ pdv1 = ’ , pdv1 )|

get this

dv1 = (18.115500431291366-7.9395797008381805j)
pdv1 = (1.6247085588602121-0.7120699283262942j)

but if i print it this way

print("DV = %3.5f V   P = %3.4f  "%(  dv1 , pdv1 ))

it does not work

TypeError: can’t convert complex to float

is it possible that this kind of print format cannot be used somehow?

can anyone explain how to make it work

note i also get an error on this one

n = 3.4 + 2.3j
print ‘%05f %05fi’ % (n.real, n.imag)
3.400000 2.300000i

which is working on

thanks
happy bl

I find that f-strings are the easiest way for me to format strings in Python.

This code runs without errors for me:

import bpy

dv1 = (18.115500431291366-7.9395797008381805j)
pdv1 = (1.6247085588602121-0.7120699283262942j)

print(f"DV = {dv1}, P = {pdv1}")

Just put an f before the quotation marks on the string, and then put any variables inside curly braces.

is it possible to format the numbers too ?

thanks
happy bl

Yes, this code will give you the first 5 decimal places for the first number, and the first four decimal places for the second:

import bpy

dv1 = (18.115500431291366-7.9395797008381805j)
pdv1 = (1.6247085588602121-0.7120699283262942j)

print(f"DV = {dv1=:.5f}, P = {pdv1=:.4f}")

That will output this:
DV = dv1=18.11550-7.93958j, P = pdv1=1.6247-0.7121j

As opposed to the original code which will give you all decimal places:
DV = (18.115500431291366-7.9395797008381805j), P = (1.6247085588602121-0.7120699283262942j)

Hope that helps!

1 Like