By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,100 Members | 2,846 Online
Bytes IT Community
+ Ask a Question
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

✓ answered by bvdet

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

Share this Question
Share on Google+
6 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
I'll bite
Expand|Select|Wrap|Line Numbers
  1. >>> int(str('123')[::-1])
  2. 321
  3. >>> 
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
  1. from collections import deque
  2.  
  3. x = 123
  4. new_x = 0
  5. while x > 0:
  6.     x, y = divmod(x, 10)
  7.     new_x = new_x*10 + y
  8. print new_x
  9.  
  10. x = 123
  11. d = deque()
  12. for num in str(x):
  13.    d.appendleft(num)
  14. print "using deque",
  15. print "".join(d) 
Sep 15 '10 #3

bvdet
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
  1. x = 12345
  2. new_str = ""
  3. for ch in str(x):
  4.     new_str = ch + new_str
  5. print int(new_str)
Sep 17 '10 #6

bvdet
Expert Mod 2.5K+
P: 2,851
Here's another way, also using built-in function divmod():
Expand|Select|Wrap|Line Numbers
  1. >>> def digits(n):
  2. ...     results = []
  3. ...     while n:
  4. ...         n, x = divmod(n, 10)
  5. ...         results.insert(0, x)
  6. ...     return results
  7. ... 
  8. >>> digits(123456789)
  9. [1, 2, 3, 4, 5, 6, 7, 8, 9]
  10. >>> sum([d*10**i for i, d in enumerate(digits(123456789))])
  11. 987654321
  12. >>> 
Nov 26 '10 #7

Post your reply

Sign in to post your reply or Sign up for a free account.