将字符串转换为复数python

2024-05-15 23:28:37 发布

您现在位置: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>

这不是我想写的真正的代码,只是一个样本


Tags: moststringis错误stdinlineargcall
3条回答

complex的构造函数拒绝嵌入的空白。把它取下来,它就可以正常工作了:

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

documentation

Note

When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.

根据来自Francisco Couzo的答案,documentation声明

When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.

删除字符串中的所有空格,然后就可以完成了,这段代码对我很有用:

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

相关问题 更多 >