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

PythonNumber Formatting

Python Problem Overview


As mentioned in the title, how do I get Python to print out +1 instead of 1?

score = +1
print score
>> 1

I know -1 prints as -1 but how can I get positive values to print with + sign without adding it in manually myself.

Thank you.

Python Solutions


Solution 1 - Python

With the % operator:

print '%+d' % score

With str.format:

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

You can see the documentation for the formatting mini-language here.

Solution 2 - Python

for python>=3.8+

score = 0.2724
print(f'{score:+g}') # or use +f to desired decimal places
# prints -> +0.2724

percentage

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

Solution 3 - Python

In case you only want to show a negative sign for minus score, no plus/minus for zero score and a plus sign for all positive score:

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

score(-1) # '-1'
score(0) # '0'
score(1) # '+1'

Solution 4 - Python

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

On python interpretor

>>> score = 1
>>> print "+"+str(score)
+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
QuestionFarshid PaladView Question on Stackoverflow
Solution 1 - PythonicktoofayView Answer on Stackoverflow
Solution 2 - PythonPabloView Answer on Stackoverflow
Solution 3 - PythonjoenteView Answer on Stackoverflow
Solution 4 - PythonAniView Answer on Stackoverflow