Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 687
Farshid Palad Avatar asked Dec 01 '11 05:12

Farshid Palad


People also ask

How do you print one number in Python?

To Print an integer in python simply pass the value in the print() function. It will output data from any Python program.

How do I print a character in one by one in Python?

Explanation of the Python program: The character index of “H” -> 0 and “e” -> 1 , “y” -> 2 and so on. We printed each character one by one using the for loop.

How do I print an integer in one line in Python?

Modify print() method to print on the same line The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.


2 Answers

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.

like image 136
icktoofay Avatar answered Sep 16 '22 22:09

icktoofay


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% 
like image 31
Pablo Avatar answered Sep 17 '22 22:09

Pablo