5 proven methods to reverse the python string in 2022

5 proven methods to reverse the python string in 2022

Vipul kunwar's photo
Vipul kunwar
·Dec 11, 2021·

16 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Table of contents

This gif showing the 5 This is December of 2021.
You're preparing Python code.
And wants to know about reversing the python string.
I'm going to show you the 5 methods to reverse the python string.

As you know, python has no in-built function for reversing the python string.
So, you've got to look at some different methods.

🎯 Here you're going to learn the 5 methods to reverse the python string.

➜ Use slicing [::-1] to reverse the python string
➜ reversed() with join() method
➜ Recursion(again & again) to reverse the string
➜ for loop to reverse the python string
➜ While loop to reverse the python string

1. Reversed the string using slice [::-1] method

Do you know what the slice means?

So, slicing means the part of something.
In python it means the part of the iterables or string.

For example,
I've a string "hello". But I want only "hel".
So, I can come up with this output with a slice.

🎯 Here are quick rules for slicing:

◍ The syntax of slicing the string is [start: end].
◍ Start is the integer value where sequence start.
◍ End is the last position where sequence ends.

String is immutable & indexed. That means you can't change the string.
But you can come up with the part of the string.
To get that part of the string I'm using indexing.
Indexing starts from 0th position.

So, 1st character ➜ 0th index, 2nd character ➜ 1st index.
For example,
h e l l o
⬇ ⬇ ⬇ ⬇ ⬇
0 1 2 3 4

➡️ Negative indexing starts from last character. It indicates by -1, -2, -3....

➡️ For example,
h e l l o
⬇ ⬇ ⬇ ⬇ ⬇
-5 -4 -3 -2 -1

So, here you can easily gain elements from the last of the string using negative indexing.

I've shown you the rules of the slicing.
Let's apply it to the "hello".

message = "hello"

📝After running the Python code, it'll give the first string with 0th index and the last character with end-1.
That means here the 0 is the first index and 3-1=2nd index is the last index.


In above example, you can see that last element is 2nd index i.e. end-1.
h ---> 0th index
e ---> 1st index
l ---> 2nd index

So, you've seen the slicing.
Now, I'm going to show you the reverse of the python string using the slice method.

Wait a minute you've to take below rules for successful reversing of the python string.

🎯 Use negative indexing because we want to reverse the string i.e. -1
🎯 Second, you've to use [::] operator
🎯 Third combine above two rules --> [::-1].
That means reverse the string from last till starting.

Let's see it by code

For example,

message = "hello"

When this code runs it gives the output:)


This is pretty easy method.
Only you've to index the variable using [::-1].
And you get your reversed python string.

In opposite, it doesn't convey the proper syntax for beginners.
However, it gives you easy & flexible reverse string in python.

2. reversed() with join() method

You can reverse the string using reversed() with join() method.
This method takes two method to reverse the python string.

Let's see both methods easily.

a). reversed() method to get reversed iterator(list, tuple, set & dictionary)

First, reversed() method reversed the sequence and come as an iterator.
For example,

message = ['h', 'e', 'l', 'l', 'o']

In the above small code you can see that reversed (seq) takes one parameter i.e. Sequence.
The sequence that going to reversed.

Below is the reversed iterator

['o', 'l', 'l', 'e', 'h']

Here, you can observe that iterator has come in reversed list.
That way, you can easily reverse sequences like list, tuple, etc.

b). join() method to joins the iterator

When you need string from iterables. You can take all iterables and join them into one string.
Thus, the return value of the join method is the string data type.
For example,

message = ["h", "e", "l", "l", "o"]

After running the code, you'll gain output as a joined string


Here, join() method joins the ["h", "e", "l", "l", "o"] as the string hello.
So whenever you want a string from iterables (list, tuple, set), it's easy to implement the join() method.

Our question was how to reverse the string using reversed() & join()?
I hope you predicted the code for it.
If not, check out below:

message = ["h", "e", "l", "l", "o"]
# first reverse the sequence
# second, join them as a string

You're thinking what's happening in above code:

Let's see code step by step:

1) Python reversed the sequence---> "o", "l", "l", "e", "h".
2) 📝 that the reversed iterable has no data type. So, I use the join() method.
3) join() method in python joins the reversed iterator as a string.
"o", "l", "l", "e", "h" ---> olleh

When you run above code, you'll get the output


You can understand this method easily. If you've understood reversed() & join() methods.
It has a clear cut syntax.

It takes some time but syntax is better than slicing.

3.Use recursion to reverse the python string

Recursion is a method that returns the itself repeatedly until particular condition satisfies.
But you know, we can reverse the python string using recursion.

With the help of the recursion you can break down the function in smaller part.
Hence, you can easily understand the bigger function.

In addition, it shows your code simple and neat.
Here, I'm going to show you the recursion in factorial.
For example,

# Program to print factorial of a number
# recursively.

# Recursive function
def recursive_factorial(n):
    if n == 1:
        return n
        return n * recursive_factorial(n-1)

# user input
num = 5

# check if the input is valid or not
if num < 0:
    print("Invalid input ! Please enter a positive number.")
elif num == 0:
    print("Factorial of number 0 is 1")
    print("Factorial of number", num, "=", recursive_factorial(num))

Let's break this code into smaller part:--->
1) You've to create a function recursive_factorial(n). The n is a number that's factorial
you want to gain.
2) After that, I've to define the if-else condition inside the function block.
3) When n =1 that means no other factorial number has to return then if block returns.
Otherwise, the else block will return. else block return until num is greater than 1.

5) Outside the function, I've given the user input to program i.e. num = 5.
6) Meanwhile, Again I'll pass the if-else statements outside the function to check whether the input is valid or not.

After python runs the code, it'll give the below output ⬇⬇⬇

Factorial of number 5 = 120

🤔 Let's see how the code worked

1) I've passed num = 5 to the function recursive_factorial(5).

2) In the function, num =5 will go through if-else block. The if condition satisfies n=1 that's not here. Thus, Python takes num = 5 to the else statement.

3) The else condition is n* recursive_factorial(n-1).
so, when n=5 then else block shows as 5*recursive_factorial(4).

4) When num = 4 will pass through the function. again it'll check the if-else statement.
And this is going to the else block because num not equal to 1.

5) Likewise, the python go to else block when num = 3 and num = 2.
When num =1 then it satisfies the if statement. and at last the number returns.

Your program follows below ⬇⬇⬇⬇⬇⬇ sequence


Here, you can see that n= 1 in recursive_factorial(1). so, it'll satisfy if statement & return 1. So, your program will become 5*4*3*2*1 = 120

Thus, you've seen how the recursion returns function again & again. until base condition satisfies.

I'm going to use recursion to reverse the string.
To know more about recursion, check out here.

Let's use python recursion to reverse the python string.

def reverse(string):
    if len(string) == 0:
        return string
        return reverse(string[1:]) + string[0]     
a = str(input("Enter the string to be reversed: "))

For simplicity break down the code & understand it.

1) Create a function--> reverse(string). Here, the parameter is a string that you want to reverse.
2) After this if-else condition present.

3) First of all, the if statement return the string if the length of the string is 0. In starting, it's not going to happen because the length of string is at least 1.
4) So, you've to go to the else statement.
Here are the things the else statement returns:-
◉ It'll add first character of the string to last of the function using --> string[0].
That every starting character of the string add to last of the returned string.
◉ Meanwhile, it pass string[1:] to the reverse() function & add it to the string[0].

5). Outside the function, I've used the input() method. This method takes input from user. Also, I've converted the input to string using--> str(input())
6). At last, I've passed the user input and displayed the input using print() statement.

Let's pass the string :-

Enter the string to be reversed: hello

First of all, this string pass through function--->reverse("hello")
Second, you can see that it has the length of the 5. so, it'll go to else statement.

Inside else statement, it follows return reverse(string[1:]) + string[0].
So, the output becomes:--> return reverse("ello")+"h".
After this step, the length of the string becomes 4.

Again, it'll go through else statement.
Thus, program follows--> return reverse("llo")+"e"+"h".

You can see the length of the reverse string is 3.
As a result, this function follows--> return reverse("lo")+"l"+"e"+"h"
Here, the length of the reverse string becomes 2.
This length is greater than 0. Hence, it'll pass through else statement again.

The else statement use return reverse(string[1:]) + string[0] again.
So, your program become return reverse("o")+"l"+"l"+"e"+"h".

Again your program doesn't satisfies the if statement.
Because length of the string is 1.
When the last time your program pass through else statement.
Your program become reverse("")+"o"+"l"+"l"+"e"+"h".

Did you know what was if statement?
If not then here's it is

if len(string) == 0:
        return string

Here, you can see that length of the reverse string is 0.
Thus, program returns the string.
At last our, output becomes "o"+"l"+"l"+"e"+"h".

As you know, + operator concatenates the string.
So, our program looks like

>>> olleh

Thus, you've seen how to reverse the string using recursion.
Here's the quick shot,

reverse("hello")   ---> string length = 5
reverse("ello")+"h"   ---> string length = 4
reverse("llo")+"e"+"h"   ---> string length = 3
reverse("lo")+"l"+"e"+"h"  ---> string length = 2
reverse("o")+"l"+"l"+"e"+"h"  ---> string length = 1
reverse("")+"o"+"l"+"l"+"e"+"h" ---> string length = 0, return the string.
⬇️ olleh

In short, you've seen the reverse string using recursion.
Here, the first element of passed string add to the last of the function
---> return reverse(string[1:]) + string[0].
This process of adding first element to the last of the function happens for each element of the string.
Such as, reverse("")+"o"+"l"+"l"+"e"+"h"---> olleh.

Recursion comes a function repeatedly until the base condition satisfies.
That means the interpreter process your code until the base condition satisfied.
You can also break your code into small parts.
As a result, you can deal easily with big programs using recursion.

4. Reverse the python string using for loop

In this section, I'm going to show you how to reverse the string using for loop.
The for loop returns the iterable sequence in each newline.
So, why we're using for loop?

Previously, I've talked about the recursion.
It reverse the python string. Although, it takes more time & memory to reverse the string.
That's why I've come to for loop.
The for loop use sequence and empty string to reverse the python string.

First of all, Let's see the for loop.

message = "hello"
for x in message:

After running the code you'll get the output:--->


Next, we're going to move to the for loop to reverse the string.

Here are three problems we've to solve:-->

● First of all, I've to come iterables in same line. That means every character should add in first
line. So, I'll use + operator.

● Second, because every element of sequence come to first line. That means we've to add
different element in first line. That's why I'm going to use python function.

Before solving two problems for loop looks like


When we solve above two problems. we get output as a:-

But last and most important we've to reverse it.
So, to know about reverse the python string you've to check the code.

Let's see what steps I'm going to follow:

● The + operator adds every iterables to the beginning of the empty string.

● When every character of the string iterated and added to the beginning of the empty string. Then we get the reverse string.

def reverse_string(string):
    str = ""
    for x in string:
        str = x+str
    return str

string = "hello"
print("The reversed string is",reverse_string(string))

When you run your code:--)

So, our for loop becomes:--> for x in "hello".
After this, every character add to the beginning of the empty string i.e.str.
First, "h" add to the beginning so, str = "h".

Second, "e" add to the beginning. Thus, str = "eh".

Meanwhile, "l" add to the beginning, str = "leh".
Likewise, "l" add again to the beginning, str = "lleh" At last, "o" add & for loop completed. so, our string return as olleh.

Thus when above code runs,it gives output:--->


In short, you can reverse the string using for loop.
You've to solve three problems I've determined.
After that, you can easily reverse the python string.

5. Reverse the python string using while loop

I'll suggest you to do reverse the string using previous methods.
You should try this method, if you want to learn about while loop or know about the while loop.

If you've only one choice. then don't choose this one to reverse the python string
I'm showing you this method because of the formality!!!


Because you'll see how the while loop works.

First, I'm going to show you how the while loop works.

a). Working of the while ➰

You can use while loop when you want to print the iterable or sequence until particular condition is True.
Also, you can use while loop when you want to increment or decrement the sequence.
Mostly, while loops handles the number's sequence.

Let's see the working of the while loop:

i = 1
while i < 6:

In above example, you can see that sequence starts from 1. and incremented by 1.
Also, the sequence displayed until value of i is less than 6.
When above code runs, it gives the output.


So, you can see when i = 6 then while loop doesn't display the value.
Also, while loop use break & continue statement.

To know about thoose you can check out here.

Let's come back to reverse the python string using while loop :

str = "hello"
reverse_string = ""
count = len(str)
while count>0:
    count = count-1

print("The reverse string is",reverse_string)

So, let's see code step by step:--->

● First, I've created a string that's gonna be reverse---> "hello"
● Second, I've created the empty reversed string. This string is the string that returns as a
reversed string.

As you know, while loop mostly use increment & decrement. That means I need number in while loop.

● Thus, third step is to find the length of the string using len(str). At last, we're going to enter inside the while loop.

So, while loop work as:--->

1] While count i.e. length of the string is greater than 0. That means to execute the while loop the length of the string should greater than 0.

2] Inside the while loop, we've indented the while block & write reverse_string+=str[count-1]. So, basically what this line means?

3]Add the each character of the string in reverse_string.
So, you would thinking why I've used count-1 inside str.
The reason behind is that indexing start from 0. That means for 1st character we've to use 0th
index, Likewise for 2nd character we've to use 1st index.

4]Here, first I've added "o" to the reverse_string. Before adding "o" count = 5.
"l" added to the last of the string because of the increment in reverse_string.---> "o"+"l".
count = 4
Again, "l" add to the last of the string ---> "o"+"l"+"l", count = 3.

Meanwhile, "e" add to the last of the string ---> "o"+"l"+"l"+"e", count =2.
At last, "h" add to the last of the string---> "o"+"l"+"l"+"e"+"h", count =1.
And the count becomes 0 & while loop finished.

At last, your output has displayed--

The reverse string is olleh

Thus, you've seen how to reverse the python string using while loop.
Basically, while loop uses increment or decrement to go to the next element.
To use index method you've to find the length of the python string.
As a result, I've created the count variable that stores length of the passed string.


In short, you've seen the 5 proven methods to reverse the python string.
As you know, python has no built-in method to reverse the string.
So, you've to combine different methods.
These methods are for different purpose.

If you want your task easily. You can use slice method.
Where you've to only use the string_variable[::-1]. But this method doesn't convey the syntax.

For more precise syntax you can use reversed() with join() method.
The reversed() method reversed the sequence & join() method joins the iterables as string.
This one convey the syntax.

Do you've a habit of breaking down the program?

Then you can use recursion. Recursion reverse the function until the condition satisfies.
Using recursion you can add starting elements to last of the function.
For that, you've to use if-else condition.
The if condition return when length of the string is 0. And else statement shows the recursion.

Next, I talked about the for loop to reverse the python string.
Here I'd passed the string through function. And created the empty string.
I've also passed the string through for loop.
When each iteration starts with, for loop each character is added to the beginning of the empty string.

At last, you got the reversed string using for loop.

While loop display the sequence until condition is True.
Here you've seen until count>0 while loop will executes. and the count is the length of the python string.
From every count, the count decrement by 1. because the count coming from last index to the first.

Thus, using while loop you can reverse the python string.

Above all methods, Do you've any simple method for reversing the python string. that you want to share then comment below. I'm waiting.

Don't forget to share!!!

This is showing don't forget emoji Also, you can check out my articles below.
This is showing check out below

1.How to grab the length of the python string?

2.3 useful methods to combine the little python strings

3.How to split the python string that gives you individual list of words?

Did you find this article valuable?

Support Vipul kunwar by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
Share this