Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a string in Python

Tags:

python

string

There is no built in reverse function for Python's str object. What is the best way of implementing this method?

If supplying a very concise answer, please elaborate on its efficiency. For example, whether the str object is converted to a different object, etc.

like image 231
oneself Avatar asked May 31 '09 02:05

oneself


People also ask

Can you use reverse () on a string?

String class does not have reverse() method, we need to convert the input string to StringBuffer, which is achieved by using the reverse method of StringBuffer.

Is there a reverse function in Python?

Python includes a built-in function that is used to create a reverse iterator: the reversed() function. This iterator works because strings are indexed, so each value in a string can be accessed individually. The reverse iterator is then used to iterate through the elements in a string in reverse order.

How do you reverse a string in Python without reverse?

for i in my_string: Now, since we are iterating, we will be using the iterating variable. We will concatenate the empty string str with the value of an iterating variable which will reverse the string one letter at a time. By end of the for loop, str will contain the given string in reverse order.


1 Answers

How about:

>>> 'hello world'[::-1] 'dlrow olleh' 

This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.

like image 87
Paolo Bergantino Avatar answered Sep 28 '22 21:09

Paolo Bergantino