How to reverse a string in Python without using reverse function

In Python, there are built-in methods for reversing a string. But sometimes you will be asked specifically to reverse a string without using any of the functions.
In this article, we will learn to reverse a string without using reverse function.
Method 1:
The first method for reversing a string other than the reverse function is using string splicing.
This is the easiest and fasted method for string reversal.
# using string splicing def rev(s): # string splicing print(s[::-1]) rev('Hello world') rev('Python') rev('string')
Output:
dlrow olleH nohtyP gnirts
Method 2:
def rev(st): s = "" for i in st: s = i + s print(s) rev('malayalam') rev('water')
Output:
malayalam retaw
Subscribe
Login
Please login to comment
0 Discussion