Python 内建函数 - complex([real[, imag]])

Python 的 complex() 内建函数用于创建复数或解析字符串为复数。该函数接受实部和虚部参数,可接受任何数值类型,若虚部未指定,默认为 0。当仅提供字符串时,该字符串将被解释为复数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Manual

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.

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.

The complex type is described in Numeric Types — int, float, complex.

直译

以实部+虚部*1j形式返回一个复数,或将字符串或数字转化为复数。如果第一个参数是字符串,它将会被转化为复数,且函数的调用不能有第二个参数,第二个参数永远不能是字符串。每个参数可以使任意数值类型(包括复数)。如果缺省虚部,它默认为0,构造器会以整数或浮点数值进行对待。如果两个参数都缺省,则返回0j。

注意:当从一个字符串转化时,字符串在中间的‘+’或‘-’操作符周围不能包含空格。例如:复数complex('1+2j')可行,但complex('1 + 2j')则会引发ValueError。

复数类型详见数值类型—整数,浮点数和复数

实例

>>> complex(0)
0j
>>> complex(3, 5)
(3+5j)
>>> complex(2.25, 163.33)
(2.25+163.33j)
>>> complex('1+2j')
(1+2j)
>>> complex('1 + 2j')
Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    complex('1 + 2j')
ValueError: complex() arg is a malformed string
>>> complex('1+2j', '6j')
Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    complex('1+2j', '6j')
TypeError: complex() can't take second arg if first is a string

拓展阅读

数值类型—整数,浮点数和复数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值