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.
StringBuilder or StringBuffer class has an in-build method reverse() to reverse the characters in the string. This method replaces the sequence of the characters in reverse order. The reverse method is the static method that has the logic to reverse a string in Java.
Reverse string in Python using an extended slice Extended slice offers to put a “step” field as [start, stop, step], and giving no field as start and stop indicates default to 0 and string length respectively, and “-1” denotes starting from the end and stop at the start, hence reversing a string.
The reversed() method computes the reverse of a given sequence object and returns it in the form of a list.
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
Code:
>>> n = 1234
>>> print str(n)[::-1]
4321
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With