Reverse a string using stack in python; Through this tutorial, i am going to show you how to reverse a string using stack in python.
In this tutorial, i will write a program to reverse a string using stack in python.
Python Program to Reverse String Using Stack
Use the following steps and write a python program to reverse string using stack;
- Get input string in program from user.
- Read string from left to right and push each string element/character in stack.
- Once the string reading is done.
- Pop each string character/element one by one and put them back to the string.
- Once the stack is empty return the result in string form.
- Print reverse a string.
class Stack_to_reverse :
# Creates an empty stack.
def __init__( self ):
self.items = list()
self.size=-1
#Returns True if the stack is empty or False otherwise.
def isEmpty( self ):
if(self.size==-1):
return True
else:
return False
# Removes and returns the top item on the stack.
def pop( self ):
if self.isEmpty():
print("Stack is empty")
else:
return self.items.pop()
self.size-=1
# Push an item onto the top of the stack.
def push( self, item ):
self.items.append(item)
self.size+=1
def reverse(self,string):
n = len(string)
# Push all characters of string to stack
for i in range(0,n):
S.push(string[i])
# Making the string empty since all characters are saved in stack
string=""
# Pop all characters of string and put them back to string
for i in range(0,n):
string+=S.pop()
return string
S=Stack_to_reverse()
seq=input("Enter a string to be reversed")
sequence = S.reverse(seq)
print("Reversed string is " + sequence)
After executing the program, the output will be:
Enter a string to be reversed hello Reversed string is olleh
Recommended Python Tutorials
Recommended:-Python Program to Count Set Bits in a Number
Recommended:-Python Program for BMI Calculation
Recommended:-Python Program to Find Out Absolute Value
Recommended:-Python Random Number Generator Code
Recommended:-Python program for Zip, Zap and Zoom game
Recommended:-Python Program to Swap Two Numbers
Recommended:-Python Program to Find n-th term of Fibonacci Series
Recommended:-Python Program For Calculator
Recommended:-Python Program to Find Strong Number
Recommended:-Python Program to Convert cm to Feet and Inches
Recommended:-How to Reverse a List in Python
Recommended:-Python Program to Convert Celsius to Fahrenheit
Recommended:-Python Program to Find Standard Deviation
Recommended:-Python Program to Check Perfect Number
Recommended:-Python Program to Display Calendar
Recommended:-Python Program to Print Alphabets from A to Z
Recommended:-Python Program to Find Roots of Quadratic Equation
Recommended:-Python Program to Find the Variance
Recommended:-How to Check Python Program Execution Time
Recommended:-Python Program Find Day of Week For Given Date
Recommended:-Python Program to Print Sum of All Array Elements