Dec 9, 2016
2 mins read
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:
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?
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.
This is the best and effective way to reverse a 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 by using another string variable and adding character one by one in the opposite of the given string.
This approach may hurt the performance of the application based on the string length.
So the best approach is to use [::-1] and fastest.