Reverse string using recursion in python

Python program for Reverse string using recursion. Here more information.

#  Reverse string using recursion in Python 3
class ReverseString :
	#  This is reversing the string elements recursively
	def reverseText(self, text, location) :
		#  Base condition to stop the recursion process
		if (location >= 0) :
			#  Recursive function call
			return str(text[location]) + \
              self.reverseText(text, location - 1)
		
		#  When no character remaining
		return ""
	
	#  This is handling the request process of reverse string elements
	def reverse(self, text) :
		#  Display given string elements
		print("Before Text : [", text ,"]",sep="")
		return self.reverseText(text, len(text) - 1)
	

def main() :
	task = ReverseString()
	text = "ABCDE"
	text = task.reverse(text)
	#  After reverse	
	print("After Text  : [", text ,"]\n",sep="")
	text = task.reverse("654A321")
	#  After reverse	
	print("After Text  : [", text ,"]\n",sep="")

if __name__ == "__main__": main()

Output

Before Text : [ABCDE]
After Text  : [EDCBA]

Before Text : [654A321]
After Text  : [123A456]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved