python格式化输出复数_格式化复数
您可以使用str.format()方法执行如下所示的操作:>>> 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)
更新-更简单的方法
尽管不能使用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))
输出:TypeError: float argument required, not complex
但是,您可以通过str.format()方法将它与复数一起使用。这不是明确的文档,而是由Format Specification Mini-Language文档暗示的,该文档只是说:f Fixed point. Displays the number as a fixed-point number. The default precision is 6.
。所以很容易被忽视。
具体来说,Python 2.7.14和3.4.6都可以使用以下代码:print(n1: {:.2f}.format(n1))
print(n2: {:.2f}.format(n2))
输出:n1: 3.10+4.20j
n2: 3.10-4.20j
这并没有像我最初的答案中的代码那样给你足够的控制权,但它肯定要简洁得多(并且自动处理正虚部和负虚部)。
更新2-f字符串
Python 3.6中添加了Formatted string literals(akaf-strings),这意味着在该版本或更高版本中也可以这样做:print(fn1: {n1:.2f}) # -> n1: 3.40+2.30j
print(fn2: {n2:.3f}) # -> n2: 3.400-2.300j
在Python 3.8.0中,支持=说明符was added到f字符串,允许您编写:print(f{n1=:.2f}) # -> n1=3.40+2.30j
print(f{n2=:.3f}) # -> n2=3.400-2.300j
您可以使用str.format()方法执行如下所示的操作:>>> 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) 更新-更简单的方法 尽管不能使用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)) 输出:TypeError: float argument required, not complex 但是,您可以通过str.format()方法将它与复数一起使用。这不是明确的文档,而是由Format Specification Mini-Language文档暗示的,该文档只是说:f Fixed point. Displays the number as a fixed-point number. The default precision is 6. 。所以很容易被忽视。 具体来说,Python 2.7.14和3.4.6都可以使用以下代码:print(n1: {:.2f}.format(n1)) print(n2: {:.2f}.format(n2)) 输出:n1: 3.10+4.20j n2: 3.10-4.20j 这并没有像我最初的答案中的代码那样给你足够的控制权,但它肯定要简洁得多(并且自动处理正虚部和负虚部)。 更新2-f字符串 Python 3.6中添加了Formatted string literals(akaf-strings),这意味着在该版本或更高版本中也可以这样做:print(fn1: {n1:.2f}) # -> n1: 3.40+2.30j print(fn2: {n2:.3f}) # -> n2: 3.400-2.300j 在Python 3.8.0中,支持=说明符was added到f字符串,允许您编写:print(f{n1=:.2f}) # -> n1=3.40+2.30j print(f{n2=:.3f}) # -> n2=3.400-2.300j