如何在 Python 中为正数打印数字的符号 +

有没有更好的方法在正数上打印数字的 + 符号?

integer1 = 10
integer2 = 5
sign = ''
total = integer1-integer2
if total > 0: sign = '+'
print 'Total:'+sign+str(total)

0应该返回0而不是 + 。

57295 次浏览
>>> print "%+d" % (-1)
-1
>>>
>>> print "%+d" % (1)
+1
>>> print "%+d" % (0)
+0
>>>

这里是 文件

更新如果由于某种原因你不能使用 %操作符,你不需要一个函数:

>>> total = -10; print "Total:" + ["", "+"][total > 0] + str(total)
Total:-10
>>> total = 0; print "Total:" + ["", "+"][total > 0] + str(total)
Total:0
>>> total = 10; print "Total:" + ["", "+"][total > 0] + str(total)
Total:+10
>>>

使用 新的字符串格式

>>> '{0:+} number'.format(1)
'+1 number'
>>> '{0:+} number'.format(-1)
'-1 number'
>>> '{0:+} number'.format(-37)
'-37 number'
>>> '{0:+} number'.format(37)
'+37 number'
# As the questions ask for it, little trick for not printing it on 0
>>> number = 1
>>> '{0:{1}} number'.format(number, '+' if number else '')
'+1 number'
>>> number = 0
>>> '{0:{1}} number'.format(number, '+' if number else '')
'0 number'

这是建议超过 %操作员

由 python 3.6开始:

>>> integer1 = 10
>>> integer2 = 5
>>> total = integer1-integer2
>>> print(f'Total: {total:+}')
Total: +5

或:

for i in range(-1,2):
print (f' {i} becomes {i:+}')

产出:

 -1 becomes -1
0 becomes +0
1 becomes +1