How to Reverse a String in Python
Here you will learn and get the example code to Reverse a String in Python using 3 different methods.
#1. Program to reverse a string in python using extended slice
1 2 3 4 5 | string = "Code Revise" print("Original String : "+string) str=string[::-1] print ("Reverse String : "+str) |
Output
Original String : Code Revise
Reverse String : esiveR edoC
#2. Program to reverse a string in Python using for loop
1 2 3 4 5 6 7 8 | string = "Code Revise" reversed_string = "" for i in range(len(string) -1, -1, -1): reversed_string += string[i] print(reversed_string) |
Output
esiveR edoC
#3. Program to reverse a string in Python using recursion
1 2 3 4 5 6 7 | def reverse_string(s): if len(s) == 0: return s else: return reverse_string(s[1:]) + s[0] print(reverse_string('Code Revise')) |
Output
esiveR edoC
Check out our other Python examples