Python reverse string | Using loop, recursion, stack, slice, reversed

The string is a sequence of character data. There is no built-in function to reverse a string. But you can use slice, loop, recursion, reversed, join, etc function to reverse a string in python.

Python reverse string Using loop, recursion, stack, slice, reversed

Way to Python reverse string

  • Loop – for-loop
  • slice
  • Recursion
  • reversed with join()
  • stack

Example of Python reverse string

We will see programs of all above method to do reverse string in python.

1. Loop (for loop)

In the example iterates to every element and join each character in the beginning so as to obtain the reversed string.


The reversed string(using loops) is : stnuHeyE

2. Slicing (Slice the String)

Using extended slice syntax: Create a slice that starts at the end of the string, and moves backwards.

The slice statement [::-1] means start at the end of the string and end at position 0, move with the step -1negative one, which means one step backwards.

It is a fastest way and pythonic way to do it.

Output: dlroW olleH

3. Recursion function

Example of reverse string in python using recursion.

The base condition of function is that if the length of the string is equal to 0, the string is returned.

If not equal to 0, the reverse function is recursively called to slice the part of the string except the first character and concatenate the first character to the end of the sliced string.

Output: esreveR

4. Reversed with join()

The reversed() function returns the reversed iterator of the string and then using join() to join elements. And the reversed order string is formed.

Output: gnirtS

5. Stack

Output: CCCBBA

Create a reverse function in python

You can create a function to reverse a string in Python. See the below example it. We are creating a function for a slice method.

Output: esreveR

Q: Reverse string in python without using function

Answer: Example of using while loop.


original = KKRR
reverse = RRKK

Q: How to user takes a string and reverses it in python?

 Answer: The program takes a string and reverses the string without using recursion.

Here is source code of the Python Program to reverse a string without using recursion.


Q: How to reverse a string in python using for loop?

Answer: Create a function then run a loop over the length of string and return the value.

Output: !dlroW olleH

Do comment if you knew any other method to do it, or you have any doubts.

IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.