f 字符串格式:显示数字符号?

f-string formatting: display number sign?

关于 python f 字符串的基本问题,但找不到答案:如何强制显示浮点数或整数的符号?即什么 f-string 使 3 显示为 +3?

使用 if 语句 if x > 0: .. "" else: .

像这样:

numbers = [+3, -3]

for number in numbers:
    print(f"{['', '+'][number>0]}{number}")

结果:

+3
-3

编辑:小时间分析:

import time

numbers = [+3, -3] * 100

t0 = time.perf_counter()
[print(f"{number:+}", end="") for number in numbers]
print(f"\n{time.perf_counter() - t0} s ")

t0 = time.perf_counter()
[print(f"{number:+.2f}", end="") for number in numbers]
print(f"\n{time.perf_counter() - t0} s ")

t0 = time.perf_counter()
[print(f"{['', '+'][number>0]}{number}", end="") for number in numbers]
print(f"\n{time.perf_counter() - t0} s ")

结果:

f"{number:+}"                    => 0.0001280000000000031 s
f"{number:+.2f}"                 => 0.00013570000000000249 s
f"{['', '+'][number>0]}{number}" => 0.0001066000000000053 s

看来我有最快的整数解法。

您可以使用 f"{x:+}" 添加带有 f 字符串的符号,其中 x 是您需要将符号添加到的 int/float 变量。有关语法的更多信息,您可以参考 documentation.

来自文档:

Option Meaning
'+' indicates that a sign should be used for both positive as well as negative numbers.
'-' indicates that a sign should be used only for negative numbers (this is the default behavior).

来自文档的示例:

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
>>> '{:+} {:+}'.format(10, -10)
'+10 -10'

以上示例使用 f-strings:

>>> f'{3.14:+f}; {-3.14:+f}'
'+3.140000; -3.140000'
>>> f'{3.14:-f}; {-3.14:-f}'
'3.140000; -3.140000'
>>> f'{10:+} {-10:+}'
'+10 -10'

打印 00 is neither positive nor negative 时的一个警告。在python、+0 = -0 = 0.

>>> f'{0:+} {-0:+}'
'+0 +0'
>>> f'{0.0:+} {-0.0:+}'
'+0.0 -0.0'

0.0-0.0是不同的对象1.

In some computer hardware signed number representations, zero has two distinct representations, a positive one grouped with the positive numbers and a negative one grouped with the negatives; this kind of dual representation is known as signed zero, with the latter form sometimes called negative zero.


1.Negative 0 in Python. Also check out Signed Zero (-0)

您可以在 f-string

中使用 :+
number=3
print(f"{number:+}")

输出 +3