Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String reversal in Python

Tags:

python

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.

like image 721
Hick Avatar asked Jun 13 '09 16:06

Hick


People also ask

Can you use reverse () on a string?

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.

Why does 1 reverse a string in Python?

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.

What does reversed () do?

The reversed() method computes the reverse of a given sequence object and returns it in the form of a list.


2 Answers

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
like image 51
Adam Rosenfield Avatar answered Oct 09 '22 06:10

Adam Rosenfield


Code:

>>> n = 1234
>>> print str(n)[::-1]
4321
like image 33
Macarse Avatar answered Oct 09 '22 06:10

Macarse