How to print the sign + of a digit for positive numbers in Python

systempuntoout picture systempuntoout · May 4, 2010 · Viewed 38.2k times · Source

Is there a better way to print the + sign of a digit on positive numbers?

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

0 should return 0 without +.

Answer

Khelben picture Khelben · May 4, 2010

Use the new string format

>>> '{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'

It's recommended over the % operator