views:

75

answers:

2

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 +.

+6  A: 
>>> print "%+d" % (-1)
-1
>>>
>>> print "%+d" % (1)
+1
>>> print "%+d" % (0)
+0
>>>

Here is the documentation.

** Update** If for whatever reason you can't use the % operator, you don't need a function:

>>> 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
>>>
John Machin
Thanks for your answer.I'm working with web.py templator and i'm not sure if i can use the string formatting % operator. Is there a Python method that return the sign of a given number?
systempuntoout
Huh? You used the `%` operator in your question! Please edit your question so that it reflects your real requirement(s).
John Machin
That's a beauty, thanks :)
systempuntoout
("+" if total > 0 else "") is 6 more characters, but a bit more direct and (IMHO) clearer.
jchl
+3  A: 

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

Khelben
0 -> `+0`, not what the OP wants.
John Machin
Yes, sorry, I've noticed the moment I hit the button. I've corrected it.
Khelben