DEV Community

YoungWonks
YoungWonks

Posted on

5 Ways to Reverse a String using Python

Alt Text

A string in programming consists of a sequence of literal characters. We use them extensively in almost every program. Hence, it’s important to know them well and be able to use their features as and when the need arises. Reversing a string is an operation that keeps coming up time and again. Here we will see 5 simple ways to reverse a string in Python3.

Reverse Indexing

This is a method that is simple but not logical to deduce. It utilizes the start-stop-step indexing on a string to produce the reversed string.
Alt Text

Using Lists

I use this method often. This helps when there are modifications to be made prior to producing a reversed list. Here we convert the string to a list, then use the inbuilt reverse method of the list and join it back into a string.
Alt Text

Reverse Iteration

This is an approach where we step through the string one by one and keep appending the characters to the end of an empty string. At the end, we get a string that is the reverse of our original string.
Alt Text

Using the Reversed Function

This reversed function is a built-in function in Python3 that allows us to reverse any sequence that is provided. It mainly accesses the sequence in the reverse order. The reversed functions work not only for a string but also for lists, tuples etc.
Alt Text

Using Indexing

This is an approach we really need to know as it is the only way we can implement this in other languages like C and C++ etc. Here we just use a loop to iterate from the end to the beginning while appending the characters to an empty string.
Alt Text

This article has been written by Suchin Ravi. Suchin is an experienced educator and technologist. Suchin teaches computer science at YoungWonks https://www.youngwonks.com and works as a lead software developer on many projects at Wonksknow https://www.wonksknow.com/.

Top comments (0)