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.

1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

renamed str -> s to avoid confusion with builtin str
4

Code:

>>> n = 1234
>>> print str(n)[::-1]
4321

Comments

2
>>> int(''.join(reversed(str(12345))))
54321

1 Comment

Note: Not as pythonic as the slicing operator solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.