444,100 Members | 2,846 Online
Need help? Post your question and get tips & solutions from a community of 444,100 IT Pros & Developers. It's quick & easy.

How do I isolate individual digits of numbers in python?

 P: 4 If i had the number 123 how would i make it 321? Sep 14 '10 #1

I'll bite
Expand|Select|Wrap|Line Numbers
1. >>> int(str('123')[::-1])
2. 321
3. >>>

6 Replies

 Expert Mod 2.5K+ P: 2,851 I'll bite Expand|Select|Wrap|Line Numbers >>> int(str('123')[::-1]) 321 >>>  Sep 14 '10 #2

 Expert 100+ P: 624 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. Expand|Select|Wrap|Line Numbers 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)  Sep 15 '10 #3

 Expert Mod 2.5K+ P: 2,851 I like that dwblas. Sep 15 '10 #4

 P: 4 thanks guys. Sep 15 '10 #5

 Expert 100+ P: 624 One more for the sake of completeness for any searchers. Expand|Select|Wrap|Line Numbers x = 12345 new_str = "" for ch in str(x):     new_str = ch + new_str print int(new_str) Sep 17 '10 #6

 Expert Mod 2.5K+ P: 2,851 Here's another way, also using built-in function divmod(): Expand|Select|Wrap|Line Numbers >>> 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 >>>  Nov 26 '10 #7