【问题标题】:How to print +1 in Python, as +1 (with plus sign) instead of 1?如何在Python中打印+1,作为+1(带加号)而不是1?
【发布时间】:2012-01-10 08:12:08
【问题描述】:

如标题所述,如何让 Python 打印出 +1 而不是 1?

score = +1
print score
>> 1

我知道 -1 打印为 -1,但是如何在不自己手动添加的情况下使用 + 号打印正值。

谢谢。

【问题讨论】:

    标签: python number-formatting


    【解决方案1】:

    the % operator:

    print '%+d' % score
    

    str.format:

    print '{0:+d}'.format(score)
    

    您可以查看格式化迷你语言here的文档。

    【讨论】:

    • 谢谢它的工作,你能解释一下它背后的格式化逻辑,这样我就可以学习它而不是记住它吗?谢谢。
    • @Capriano:+ 表示数字应该以+ 开头,如果它是正数(或者- 如果负数)。 d 表示该数字应以十进制表示(以十为底)。
    • 只是想知道@icktoofay 现在是否将分数视为浮点数/双精度数? (我知道在 c %d 中指的是一个 int 变量。
    • @John:不;像 C 一样,f 用于 floats 和 doubles; d 用于十进制整数。
    • +1 为我拉一个。那很好,我没有正确思考。
    【解决方案2】:

    python>=3.8+

    score = 0.2724
    print(f'{score:+d}')
    # prints -> +0.2724
    

    百分比

    score = 0.272425
    print(f'{score:+.2%}')
    # prints -> +27.24%
    

    【讨论】:

      【解决方案3】:

      如果您只想为负分显示负号,零分不显示加号/减号,所有正分都显示加号:

      score = lambda i: ("+" if i > 0 else "") + str(i)
      
      score(-1) # '-1'
      score(0) # '0'
      score(1) # '+1'
      

      【讨论】:

        【解决方案4】:
        score = 1
        print "+"+str(score)
        

        关于python解释器

        >>> score = 1
        >>> print "+"+str(score)
        +1
        >>>
        

        【讨论】:

        • 谢谢ani,但是正如ice 解释的那样,我需要python 来为我做这件事,而不是手动添加t。
        猜你喜欢
        • 1970-01-01
        • 2021-07-04
        • 2021-08-17
        • 1970-01-01
        • 2017-08-29
        • 1970-01-01
        • 2018-07-23
        • 1970-01-01
        • 2013-06-16
        相关资源
        最近更新 更多