2017-03-08 612 views
1

即時嘗試將輸入的字符串轉換爲浮點數,但是當我這樣做時,我不斷收到某種錯誤,所以下面是我做的一個樣例。 Im相當肯定我沒有做錯任何事,但如果你發現任何錯誤將字符串轉換爲複數python

 >>> a = "3 + 3j" 
    >>> b=complex(a) 
    >>> 
    ValueError: complex() arg is a malformed string 
    >>> Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    c= complex("3 + 3j") 
    >>> 
    ValueError: complex() arg is a malformed string 
    >>> Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 

PS是不實際的代碼,我嘗試寫只是一個樣本

+0

應該是:'一個= 「3 + 3J」'。 – vanloc

+1

在一個事情不完全無關,這段代碼告訴我complexValue沒有定義 –

回答

5

documentation

從字符串轉換時,該字符串不得在中心+或 - 運算符周圍包含空格 。例如,complex('1+2j')是 罰款,但complex('1 + 2j')增加ValueError

+0

非常感謝...解決方案是如此簡單,我覺得很蠢 –

0

complex的構造函數拒絕嵌入的空白。刪除它,它會工作得很好:

>>> complex(''.join(a.split())) # Remove all whitespace first 
(3+3j) 
3

繼從Francisco Couzco答案,documentation指出

當從字符串轉換,該字符串不能包含圍繞中心+空格或 - 運營商。例如,complex('1 + 2j')很好,但複雜('1 + 2j')會引發ValueError。

取下字符串中的所有空格,你就會把它完成,此代碼的工作對我來說:

a = "3 + 3j" 
a = a.replace(" ", "") # will do nothing if unneeded 
b = complex(a) 
+0

非常好的第一篇文章! – Gang