【问题标题】:f-string formatting: display number sign?f 字符串格式:显示数字符号?
【发布时间】:2022-01-20 07:28:30
【问题描述】:

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

【问题讨论】:

  • 您是否正在寻找类似行显示的解决方案? (没有任何声明?)

标签: python python-3.x string f-string


【解决方案1】:

来自文档:

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中,零有两种不同的表示,一个正数与正数分组,一个负数与负数分组;这种对偶表示称为有符号零,后一种形式有时称为负零。


1.Negative 0 in Python。另请查看Signed Zero (-0)

【讨论】:

    【解决方案2】:

    像这样:

    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
    

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

    【讨论】:

    • 有点神秘,但我喜欢这个解决方案,使用 number>0 的结果作为索引!非常聪明。
    • 这似乎不是预期的解决方案^^而且它比其他解决方案慢!!
    【解决方案3】:

    你可以在 f-string 中使用:+

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

    输出 +3

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-05-02
          • 2019-05-23
          • 1970-01-01
          • 2021-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多