python - Best way to add a "+" and "-"? -
what best way display either + in front, float? lets if user inputs number "10". want have "+" appear in front of since positive number. if negative number leave is.
would have use if statement , convert string , add in + sign? or there easier way?
use format()
function:
>>> format(10, '+f') '+10.000000' >>> format(-10, '+f') '-10.000000' >>> format(3.14159, '+.3f') '+3.142'
see format specification mini-language specific formatting options; prepending number format +
makes include plus positive numbers, -
negative. last example formats number use 3 decimals, example.
if need remove negative sign, you'd have explicitly using .lstrip()
:
>>> format(10, '+f').lstrip('-') '+10.000000' >>> format(-10, '+f').lstrip('-') '10.000000'
but that'd quite confusing specification read, in opinion. :-)
Comments
Post a Comment