Reverse a string in Python using a loop

In this example, we call a function to reverse a string, which iterates to every element and intelligently joins each character in the beginning so as to obtain the reversed string. 

Time complexity: O(n) 
Auxiliary Space: O(1) 

Implementation:

Python3




def reverse(s):
    str = ""
    for i in s:
        str = i + str
    return str
 
s = "w3wiki"
 
print("The original string is : ", end="")
print(s)
 
print("The reversed string(using loops) is : ", end="")
print(reverse(s))


Output

The original string is : w3wiki
The reversed string(using loops) 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

Similar Reads

Reverse a string in Python using a loop

In this example, we call a function to reverse a string, which iterates to every element and intelligently joins each character in the beginning so as to obtain the reversed string....

Reverse a string in Python using recursion

...

Reverse string in Python using stack

The string is passed as an argument to a recursive function to reverse the string. In the function, the base condition is that if the length of the string is equal to 0, the string is returned. If not equal to 0, the reverse function is recursively called to slice the part of the string except the first character and concatenate the first character to the end of the sliced string. ‘...

Reverse string in Python using an extended slice

...

Reverse string in Python using reversed() method

An empty stack is created. One by one character of the string is pushed to the stack. One by one all characters from the stack are popped and put back to a string....

Reverse string in Python using list comprehension()

...

Reverse string in Python using the function call

Extended slice offers to put a “step” field as [start, stop, step], and giving no field as start and stop indicates default to 0 and string length respectively, and “-1” denotes starting from the end and stop at the start, hence reversing a string....