您可以使用如下所示的方法进行操作str.format()
method:
>>> n = 3.4+2.3j
>>> n
(3.4+2.3j)
>>> '({0.real:.2f} + {0.imag:.2f}i)'.format(n)
'(3.40 + 2.30i)'
>>> '({c.real:.2f} + {c.imag:.2f}i)'.format(c=n)
'(3.40 + 2.30i)'
为了使其正确处理正虚部和负虚部,您将需要(甚至更)复杂的格式化操作:
>>> n = 3.4-2.3j
>>> n
(3.4-2.3j)
>>> '({0:.2f} {1} {2:.2f}i)'.format(n.real, '+-'[n.imag < 0], abs(n.imag))
'(3.40 - 2.30i)'
更新 - 更简单的方法
虽然你cannot use f
作为使用字符串格式化运算符的复数的表示类型%
:
n1 = 3.4+2.3j
n2 = 3.4-2.3j
try:
print('test: %.2f' % n1)
except Exception as exc:
print('{}: {}'.format(type(exc).__name__, exc))
Output:
TypeError: float argument required, not complex
You can但是通过以下方式将其与复数一起使用str.format()
方法。这没有明确记录,但隐含在格式规范迷你语言 https://docs.python.org/3/library/string.html?highlight=formatting#format-specification-mini-language文档只是说:
'f'
固定点。将数字显示为定点数。默认精度为6
.
。 。 .所以很容易被忽视。
具体而言,以下内容在 Python 2.7.14 和 3.4.6 中均有效:
print('n1: {:.2f}'.format(n1))
print('n2: {:.2f}'.format(n2))
Output:
n1: 3.10+4.20j
n2: 3.10-4.20j
这并不能让您完全控制我原来答案中的代码,但它肯定更加简洁(并且自动处理正虚部和负虚部)。
更新2 -F 弦
格式化字符串文字 https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals (aka F 弦) 是在 Python 3.6 中添加的,这意味着在该版本或更高版本中也可以这样完成:
print(f'n1: {n1:.2f}') # -> n1: 3.40+2.30j
print(f'n2: {n2:.3f}') # -> n2: 3.400-2.300j
在 Python 3.8.0 中,支持=
说明符加入 https://docs.python.org/3.8/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging到 f 字符串,允许您编写:
print(f'{n1=:.2f}') # -> n1=3.40+2.30j
print(f'{n2=:.3f}') # -> n2=3.400-2.300j