ProgrammingPython

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. 

# 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.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button