繁体   English   中英

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

[英]How to print +1 in Python, as +1 (with plus sign) instead of 1?

正如标题中提到的,如何让 Python 打印出 +1 而不是 1?

score = +1
print score
>> 1

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

谢谢你。

使用%运算符

print '%+d' % score

使用str.format

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

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

对于python>=3.8+

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

百分比

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

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

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

score(-1) # '-1'
score(0) # '0'
score(1) # '+1'
score = 1
print "+"+str(score)

在 python 解释器上

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM