tags:

views:

588

answers:

3

I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?

I am not able to convert the integer into a list so not able to apply the reverse fuction.

+3  A: 

Code:

>>> n = 1234
>>> print str(n)[::-1]
4321
Macarse
+19  A: 

You can use the slicing operator to reverse a string:

s = "hello, world"
s = s[::-1]
print s  # prints "dlrow ,olleh"

To convert an integer to a string, reverse it, and convert it back to an integer, you can do:

x = 314159
x = int(str(x)[::-1])
print x  # prints 951413
Adam Rosenfield
Haven't seen this method before..
Armandas
renamed str -> s to avoid confusion with builtin str
J.F. Sebastian
@J.F. Sebastian, thanks, that was rather foolish of me =/
Adam Rosenfield
+2  A: 
>>> int(''.join(reversed(str(12345))))
54321
Armandas
Note: Not as pythonic as the slicing operator solution.
Macarse
I agree, but only learnt that method today :)
Armandas