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

PythonString Formatting

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

From python 3.6 onwards:

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

or:

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

outputs:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsystempuntooutView Question on Stackoverflow
Solution 1 - PythonKhelbenView Answer on Stackoverflow
Solution 2 - PythonJohn MachinView Answer on Stackoverflow
Solution 3 - PythonErichBSchulzView Answer on Stackoverflow