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)) |
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