Skip to content

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

  • by

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.

s = "EyeHunts"

str = ""
for i in s:
    str = i + str

print("The reversed string(using loops) is : ", end="")
print(str)

Output:

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 backward.

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

str = "Hello World"[::-1]
print(str)

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.

def reverse(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]


print(reverse("Python"))

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.

def reverse(string):
    string = "".join(reversed(string))
    return string

print(reverse("String"))

Output: gnirtS

5. Stack

def revstring(mystr):
    myStack = []  # this is how i have myStack

    for ch in mystr:
        myStack.append(ch)  # push the characters to form a stack

    revstr = ''  # form an empty reverse string
    while len(myStack):
        # adding my characters to the empty reverse string in reverse order
        revstr = revstr + myStack.pop()

    return revstr


print(revstring("ABBCCC"))

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.

def rev_function(x):
    return x[::-1]


mytxt = rev_function("Reverse")

print(mytxt)

Output: esreveR

Q: Reverse string in python without using function

Answer: Example of using while loop.

string1 = "KKRR"
string2 = ""

i = len(string1) - 1

while (i >= 0):
    string2 = string2 + string1[i]
    i = i - 1

print("original = " + string1)
print("reverse  = " + string2)

Output:

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.

a = str(input("Enter a string: "))
print("Reverse of the string is: ")
print(a[::-1])

Output:

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.

def reverse(text):
    a = ""
    for i in range(1, len(text) + 1):
        a += text[len(text) - i]
    return a

print(reverse("Hello World!"))

Output: !dlroW olleH

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

Note:
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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading