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)
print '{0:+d}'.format(score)
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看格式化迷你语言的文档.
为了 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)
如果您只想显示负分的负号,零分没有加/减,所有正分都显示加号:
score = lambda i: ("+" if i > 0 else "") + str(i)
score(-1) # '-1'
score(0) # '0'
score(1) # '+1'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21045 次 |
| 最近记录: |