Reverse string in Python using list comprehension()
List comprehension creates the list of elements of a string in reverse order and then its elements are joined using join(). And reversed order string is formed.
Time complexity: O(n)
Auxiliary Space: O(1)
Implementation:
Python3
# Function to reverse a string def reverse(string): string = [string[i] for i in range ( len (string) - 1 , - 1 , - 1 )] return "".join(string) s = "w3wiki" print ( "The original string is : " , s) print ( "The reversed string(using reversed) is : " , reverse(s)) |
The original string is : w3wiki The reversed string(using reversed) is : skeegrofskeeG
Reverse string in Python (6 different ways)
Python string library doesn’t support the in-built “reverse()” as done by other python containers like list, hence knowing other methods to reverse string can prove to be useful. This article discusses several ways to achieve it in Python.
Example:
Input: w3wiki
Output: skeegrofskeeG