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 +.
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.
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.
%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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With