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

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


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.


for python>=3.8+

score = 0.2724print(f'{score:+d}')# prints -> +0.2724

percentage

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


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'