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
  • 34,448
  • 50
  • 182
  • 322
Hick
  • 35,524
  • 46
  • 151
  • 243

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
  • 399,953
  • 195
  • 994
  • 1,670
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
4

Code:

>>> n = 1234
>>> print str(n)[::-1]
4321
Macarse
  • 91,829
  • 44
  • 175
  • 230
2
>>> int(''.join(reversed(str(12345))))
54321
Armandas
  • 2,276
  • 1
  • 22
  • 27