5 Ways to Reverse String in Python

Hello everyone, in this tutorial we’ll see different ways to reverse string in Python.

As we know, we can reverse a list using reverse() method but Python doesn’t have the reverse() method for string.

Here are some alternate and easy ways to reverse a string.

Ways to Reverse String in Python

1. Using Loop

Output:

original = the crazy programmer
reverse = remmargorp yzarc eht

In above program, we’ve started a loop from the last index (length-1) to first index (0) of string1. In each step of loop, it will pick the character from right-side in string1 and concatenate with string2.

2. Using Recursion

In above program, there is a reverse_it() method which accepts a string and then it will check if the string is empty or not, if empty then it will return the string otherwise it will call itself by passing string from its second character to last character.

String = “hello”

Print string[1:]

Output:  ‘ello’

After calling reverse_it() method again and again there will be a point when string will be empty then the condition

if len(string) == 0:

will be true , it will return the string.  return statement will throw the execution, where it came from.

So in

Return reverse_it(string[1:])  +  string[0]

the “+ string[0] “ will be executed next, which will add the first letter at last.

3. Using Stack

In above program, we’re using concept of stack having push and pop functions.

To implement stack concept we’re using list.

When we call reverse() method, it will create a list named as ‘stack’ and insert all the characters of string into list using push() method. At last it will fetch all the elements in the list from last to first one by one and store them into the string.

4. Using Extended Slice

Mostly extended slice is used for skipping the steps but if we put -1 in third ‘step’ or ‘stride’ argument then we can get the reverse of a string, list and tupple.

5. Using List

String doesn’t have reverse() method but lists have. So we are converting string into list, performing reverse() operation and again converting it back into string using ‘ ’.join() method.

Comment below if you have queries or know any other way to reverse a string in python.

1 thought on “5 Ways to Reverse String in Python”

  1. Beginner here, why does [::-1] make it reversed? I tried looking it up but cant find any meaning on the double colon.

Leave a Comment

Your email address will not be published. Required fields are marked *