How can I convert a negative number to positive in Python? (And keep that positive value.)
+11
A:
>>> n = -42
>>> -n # if you know n is negative
42
>>> abs(n) # for any n
42
Don't forget to check the docs.
Roger Pate
2010-10-04 10:26:48
[abs](http://docs.python.org/library/functions.html#abs)
Roger Pate
2010-10-04 10:29:56
@Roger: add the link to the doc in the body of the answer instead? It took me a moment to realise that your comment had a link.
Manoj Govindan
2010-10-04 10:33:26
`-n` is enlightening
dhill
2010-10-04 11:12:16
+6
A:
If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use abs()
:
>>> abs(-1)
1
>>> abs(1)
1
BoltClock
2010-10-04 10:27:18
+4
A:
The inbuilt function abs() would do the trick.
positivenum = abs(negativenum)
Tim
2010-10-04 10:27:28
+2
A:
In [6]: x = -2
In [7]: x
Out[7]: -2
In [8]: abs(x)
Out[8]: 2
Actually abs
will return the absolute value
of any number. Absolute value is always a non-negative number.
Tauquir
2010-10-04 10:42:40