Python:将字符串对转换为复数

P i*_*P i 0 python type-conversion complex-numbers

这是我的复数:我正在从文件中检索它.

        re, im = line[11:13]
        print( re ) # -4.04780617E-02
        print( im ) # +4.09889424E-02
Run Code Online (Sandbox Code Playgroud)

目前它只是一对弦.如何将这些组合成一个复数?

我已经尝试了五次.

        z = complex( re, im )
        # ^ TypeError: complex() can't take second arg if first is a string

        z = complex( float(re), float(im) )
        # ^ ValueError: could not convert string to float: re(tot)

        z = float(re) + float(im) * 1j
        # ^ ValueError: could not convert string to float: re(tot)

        z = complex( "(" + re + im + "j)" )
        # ValueError: complex() arg is a malformed string

        z_str = "(%s%si)" % (re, im) # (-4.04780617E-02+4.09889424E-02i)
        z = complex( z_str )
        # ValueError: complex() arg is a malformed string
Run Code Online (Sandbox Code Playgroud)

Ivo*_*ijk 5

Python使用'j'作为虚部的后缀:

>>> complex("-4.04780617E-02+4.09889424E-02j")
(-0.0404780617+0.0409889424j)
Run Code Online (Sandbox Code Playgroud)

在你的情况下,

z_str = "(%s%sj)" % (re, im) # (-4.04780617E-02+4.09889424E-02i)
z = complex( z_str )
Run Code Online (Sandbox Code Playgroud)