[Tutor] Re: reverse a number (was no subject)
Lance E Sloan
lsloan@umich.edu
Fri, 23 Aug 2002 09:49:17 -0400
--On Thursday, August 22, 2002 9:21 AM -0700 Sean 'Shaleh' Perry
<shalehperry@attbi.com> wrote:
>> How about converting the number to a list and then reversing the elements
>> now:
>>
>> m=list(str(int(number)))
>> m.reverse()
>> numString=''.join(m) #this is your reversed number as a string
>>
>
> or the old school C way (-:
>
>>>> l = []
>>>> n = 321
>>>> while n:
> ... l.append(n % 10)
> ... n /= 10
> ...
>>>> l
> [1, 2, 3]
Sure. And while we're in that neighborhood, we might as well be even more
C-like and leave out the list:
>>> n = 321
>>> m = 0
>>> while n:
... m = m * 10 + n % 10
... n /= 10
...
>>> m
123
--
Lance E Sloan
Web Services, Univ. of Michigan: Full-service Web and database design,
development, and hosting. Specializing in Python & Perl CGIs.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"