How do I isolate individual digits of numbers in python?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kevow123
    New Member
    • Sep 2010
    • 4

    How do I isolate individual digits of numbers in python?

    If i had the number 123 how would i make it 321?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    I'll bite
    Code:
    >>> int(str('123')[::-1])
    321
    >>>

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      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

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        I like that dwblas.

        Comment

        • kevow123
          New Member
          • Sep 2010
          • 4

          #5
          thanks

          thanks guys.

          Comment

          • dwblas
            Recognized Expert Contributor
            • May 2008
            • 626

            #6
            One more for the sake of completeness for any searchers.
            Code:
            x = 12345
            new_str = ""
            for ch in str(x):
                new_str = ch + new_str
            print int(new_str)

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              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

              Working...