Introduction
Python comes with tons of libraries and inbuilt functions. There are libraries for data science, machine learning, maths etc. Often these inbuilt function comes in handy when doing a certain task in Python. Take the case of string reversal in Python. There are different ways to reverse a string in Python.
In this blog, we will learn How to Reverse a String in Python.
You can also read about the Multilevel Inheritance in Python, Swapcase in Python
Methods of Reversing a String in Python
1. Reverse a string in Python using a loop
In this method, the string is revered using Python ‘for loop’. We iterate over all the characters in the strings and concatenate them in reverse order.
Program
Output
Original String is: Coding Ninjas
[Using loop]Reversed String is: sajniN gnidoC
2. Reverse a string in Python using recursion
In this method, the string is reversed using recursion. The base case is when only a single character is left in the string.
Program
Output
Original String is: Coding Ninjas
[Using recursion]Reversed String is: sajniN gnidoC
3. Reverse a string in Python using Stack
In this method, the string is reversed using “stack.” We will take an empty list as a stack and push all the characters in it. The elements from the reversed order will be at the top of the stack. We will add the elements from the top to our empty string and pop the characters from the stack until it becomes empty.
Program
Output
original string is : Python Compiler
reversed string is : relipmoC nohtyP
4. Reverse a string using an extended slice
In this method, the string is reversed using the Python slice operator.
Program
Output
Original String is: Coding Ninjas
[Using extended slice operator]Reversed String is: sajniN gnidoC
5. Reverse a string using reversed() method
Here we are using the inbuilt reversed() function. It will return a list of characters in reversed order. We will join these characters into a resultant string.
Program
Output
original string is : Resources
reversed string is : secruoseR
6. Reverse a string in Python using list comprehension Method()
In this method, the string is reversed using a list comprehension method. We will create a new list by iterating over the string in reverse order. At last we will join all the elements of a list into a single string.
Program
Output
original string is : contests and Events
reversed string is : stnevE dna stsetnoc
7. Reverse a string using the function call
In this method, we will reverse a string using the function call. The function will take the original string as a parameter and return the reversed string. Here, we’ve used slicing technique to reverse a string inside a function.
Program
Output
original string is : Online Compiler
reversed string is : relipmoC enilnO
You can practice by yourself with the help of online python compiler.
You can also check out Reverse A String In C