Like a list reverse() method, we do not have a reverse method for Python strings. But we can use some techniques which can reverse a specified string. Here in this tutorial, we have provided some of the common techniques we can use to reverse a string in Python.
How to Reverse a string in Python?
1. Reverse a String Using Slicing
String slicing is a technique which is used to select or display a sequence of characters from a string. String slicing is the most common technique to reverse a string in python. As python string support negative indexing, which help the developer to select the string characters from the end.
Example:
Output
2. Reverse a String using the While loop
Using a while loop we can traverse from the last index value of the string to the 0 th index value. With each iteration we save the value in a temporary string and when the iteration end we would print that string.
Example
Output
< Note >: Similarly, we can use a for loop to reverse a string
Example
Output
3. Python string method join() and reversed() function
- join(): join() is the python string method which accepts an iterable object, join all its elements and return a string.
- reverse() is a python inbuilt function which accepts an iterable object(string, list, tuple, etc) and returns an iterator object in reverse order.
Example
Output
4. Reverse a Python list use join() and list() functions
- list() is a python inbuilt type conversion function which can convert an iterable object to a list.
- join(): join() is the python string method which accepts an iterable object, join all its elements and return a string.
Example
Output
5. Reverse a Python list using Recursion
In recursion, a function keeps calling itself until a base condition gets satisfied.
Example
Output
Conclusion
An algorithm would be considered the best if it gives the result in the least time or it has the best time complexity. All the techniques we have mentioned above among those the slicing technique gives result in the least time. slicing < list() and join < reversed() and join() < for loop < while loop < recursion.
People are also reading:
- How to Generate Random Data in Python?
- Python List Comprehension
- Manage Files in Python
- Python Email Extractor
- Extract all Website Links in Python
- Python User-Define Exception
- How to Use Threads for IO Tasks in Python?
- Python Convert HTML Tables into CSV Files
- Generate and Read QR Code in Python
- Numpy Matrix Multiplication
Leave a Comment on this Post