【发布时间】:2022-01-20 07:28:30
【问题描述】:
关于python f-strings的基本问题,但找不到答案:如何强制显示浮点数或整数的符号?即什么 f-string 使 3 显示为 +3?
【问题讨论】:
-
您是否正在寻找类似行显示的解决方案? (没有任何声明?)
标签: python python-3.x string f-string
关于python f-strings的基本问题,但找不到答案:如何强制显示浮点数或整数的符号?即什么 f-string 使 3 显示为 +3?
【问题讨论】:
标签: python python-3.x string f-string
来自文档:
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'
将0 打印为0 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。
在某些计算机硬件signed number representations中,零有两种不同的表示,一个正数与正数分组,一个负数与负数分组;这种对偶表示称为有符号零,后一种形式有时称为负零。
【讨论】:
像这样:
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-string 中使用:+
number=3
print(f"{number:+}")
输出
+3
【讨论】:
您可以使用 f"{x:+}" 添加带有 f 字符串的符号,其中 x 是您需要添加符号的 int/float 变量。有关语法的更多信息,您可以参考documentation。
【讨论】:
使用 if 语句 if x > 0: .. "" else: .
【讨论】: