Hello everyone, in this post I will provide you 5 different ways to reverse a string using python programming.
1
Using Slicing
def StrRev(string):
string = string[::-1]
return string
s = input("Enter a string: ")
print (StrRev(s))
2
Using Reversed Function
def StrRev(string):
string = "".join(reversed(string))
return string
s = input("Enter a string: ")
print (StrRev(s))
3
Using Loop
def StrRev(s):
strg = ""
for i in s:
strg = i + strg
return strg
s = input("Enter a string: ")
print (StrRev(s))
4
Using Recursive function
def StrRev(s):
if len(s) == 0:
return s
else:
return StrRev(s[1:]) + s[0]
s = input("Enter a string: ")
print(StrRev(s))
5
Using Stack Operations
def StackCreate():
stack=[]
return stack
def isEmpty(stack):
if len(stack) == 0:
return true
def push(stack,item):
stack.append(item)
def pop(stack):
if isEmpty(stack): return
return stack.pop()
def StrRev(string):
n = len(string)
stack = StackCreate()
for i in range(0,n,1):
push(stack,string[i])
string=""
for i in range(0,n,1):
string+=pop(stack)
return string
s = input("Enter a string: ")
print (StrRev(s))
Top comments (0)