How to reverse a string in Python?
A complete guide to reversing a string data type in Python
Python is a no-bullshit general-purpose programming language with an army of built-in libraries. Using polymorphism, we can use standard functions with a wide variety of data structures.
This is why it’s extremely strange that the Python String Library doesn’t support the built-in reverse()
function.
So, I decided to write an article discussing several ways of reversing a string in Python. I will also try to judge each of these methods based on execution speed and code clarity.
Some common ways to reverse a string are as follows:
- Slicing
- Appending characters in reverse order using a loop
- Using
reversed()
iterator - Using the built-in
reverse()
function - Recursion
Reversing a list using Slicing
Python Slicing allows us to extract a part of a sequence. This is a very direct way of reversing a list without affecting the original list.
original_string = "ABCDE"
reversed_string = original_string[::-1]print("Original String : ", original_string)
print("Reversed String : "…