If i had the number 123 how would i make it 321?
How do I isolate individual digits of numbers in python?
Collapse
X
-
Add 2 to the first digit and subtract 2 from the last digit?
or add 198 to the first number??
This code was done for some reason some time ago but I don't remember why.Code:from collections import deque x = 123 new_x = 0 while x > 0: x, y = divmod(x, 10) new_x = new_x*10 + y print new_x x = 123 d = deque() for num in str(x): d.appendleft(num) print "using deque", print "".join(d)Comment
-
Here's another way, also using built-in function divmod():
Code:>>> def digits(n): ... results = [] ... while n: ... n, x = divmod(n, 10) ... results.insert(0, x) ... return results ... >>> digits(123456789) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> sum([d*10**i for i, d in enumerate(digits(123456789))]) 987654321 >>>
Comment
Comment