Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 968
systempuntoout Avatar asked May 04 '10 07:05

systempuntoout


People also ask

How do I print a number sign in Python?

sign() in Python. numpy. sign(array [, out]) function is used to indicate the sign of a number element-wise. For integer inputs, if array value is greater than 0 it returns 1, if array value is less than 0 it returns -1, and if array value 0 it returns 0.

How do you print positive values in Python?

Example #1: Print all positive numbers from given list using for loop Iterate each element in the list using for loop and check if number is greater than or equal to 0. If the condition satisfies, then only print the number.

What does %d and %S mean in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values.

How do I print only positive numbers in a list Python?

Using the “lambda” function: As we know, the lambda function applies the condition in each element. So, Using lambda we can check whether the number is greater than zero or not. If it is greater than zero, It will print the list of all positive numbers.


1 Answers

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

like image 127
Khelben Avatar answered Oct 08 '22 12:10

Khelben