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.
# Python code to reverse a string # using list comprehension() # Function to reverse a string def reverse(string): string = [string[i] for i in range(len(string)-1, -1, -1)] return "".join(string) s ="CodeHunger"; print ("The original string is : ",s) print ("The reversed string(using reversed) is : ", reverse(s))
Output
The original string is : CodeHunger The reversed string(using reversed) is : regnuHedoC
Time complexity: O(n)
Auxiliary Space: O(1)
Explanation: List comprehension create the list of elements of a string in reverse order and then its elements are joined using join(). And reversed order string is formed.
Do you want to hire us for your Project Work? Then Contact US.