Reverse String in Python – Best Approach Given

There are many ways to reverse string in Python. If you are familiar with c , c++ and java and don’t want to use any reverse function then someone could write the logic like:

1. Using the swapping last char with first and do that until the middle character. Remember we used to do this kind of exercise in C, 101?

2. Second would be like to take a new string and add 1 by 1 character from the opposite order of the String. This may take up too much space if you have Essay to reverse.

Note: String is immutable in Python similar to in Java. So it will not change the string if you try to modify, it will create the new String.

Firstly I have not seen a use case where I need to reverse a string unless you are trying to work on Cryptography.

This is enough talking.

Let’s do the reverse string with Python.

Reverse String in Python – Best Approach

This is the best and effective way to reverse a string.

string_sample = "Hello World"

reversed_string  = string_sample[::-1]

print(reversed_string)

This is the very astonished result by writing [::-1] it reverse the String and this is the fastest way to reverse a string.

This is called extended slice syntax. It works by writing [begin:end:step] – (minus sign) by leaving begin and end off and by writing a step of -1 , this will reverse a string.

Here are some other ways to reverse a string in python.

Reverse a String using the recursive function.

def reverse(string):
    if len(string) <= 1:
        return string

    return reverse(string[1:]) + string[0]

string_sample = "Hello World"

print(reverse(string_sample))

 

Reverse a string by using another string variable and adding character one by one in the opposite of the given string.

def reverse(string):
    new_string = ''
    index = len(string)
    while index:
        index -= 1                    
        new_string += string[index] 
    return new_string

string_sample = "Hello World"
print(reverse(string_sample))

This approach may hurt the performance of the application based on the string length.