7

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 function.

BenMorel
  • 31,815
  • 47
  • 169
  • 296
Hick
  • 33,822
  • 46
  • 145
  • 240

3 Answers3

30

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
jfs
  • 374,366
  • 172
  • 933
  • 1,594
Adam Rosenfield
  • 375,615
  • 96
  • 501
  • 581
4

Code:

>>> n = 1234
>>> print str(n)[::-1]
4321
Macarse
  • 89,619
  • 44
  • 170
  • 229
2
>>> int(''.join(reversed(str(12345))))
54321
Armandas
  • 1,690
  • 1
  • 17
  • 24