如何在Python中打印+1,如+1(带加号)而不是1?

Far*_*lad 41 python number-formatting

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

score = +1
print score
>> 1
Run Code Online (Sandbox Code Playgroud)

我知道-1打印为-1但是我如何获得正值以+符号打印而不用手动添加它.

谢谢.

ick*_*fay 61

随着%操作:

print '%+d' % score
Run Code Online (Sandbox Code Playgroud)

str.format:

print '{0:+d}'.format(score)
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看格式化迷你语言的文档.

  • 谢谢,它有效,你能解释一下它背后的格式逻辑,这样我就可以学习它而不是记住它吗?谢谢你。 (3认同)
  • @Capriano:`+`表示如果数字是正数,则应该以"+"开头格式化(或者如果是负数,则应为`-`).`d`表示该数字应以十进制表示(十进制). (3认同)
  • @John:[decimal](https://en.wikipedia.org/wiki/Decimal)我的意思是十点. (3认同)

Pab*_*blo 7

为了 python>=3.8+

score = 0.2724
print(f'{score:+d}')
# prints -> +0.2724
Run Code Online (Sandbox Code Playgroud)

百分比

score = 27.2425
print(f'{score:+.2%}')
# prints -> +27.24%
Run Code Online (Sandbox Code Playgroud)


joe*_*nte 5

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

score = lambda i: ("+" if i > 0 else "") + str(i)

score(-1) # '-1'
score(0) # '0'
score(1) # '+1'
Run Code Online (Sandbox Code Playgroud)