In this post we'll see how to write a Python program to reverse a string, there are several options to do that, the options given in this post are listed below-
- Using a loop to reverse a string.
- Using a recursive function.
- Using string slicing
- Using reversed() function and join() method
Using loop to reverse a string Python program
If you are asked to write Python program to reverse a string without using any inbuilt function or string method you can use a loop to add characters of a string in a reverse order in each iteration to form a new String.
def reverse_string(string): rstring = '' for char in string: rstring = char + rstring return rstring s = 'Python Programming' rstring = reverse_string(s) print('Original String-', s, 'Reversed String-', rstring)
Output
Original String- Python Programming Reversed String- gnimmargorP nohtyP
Using recursive function to reverse a string
In recursive function, in each recursive call to the function you pass the sliced string where start index is 1 (i.e. exclude first char (index 0) in each call) and add the first char of the passed String at the end.
def reverse_string(string): if len(string) == 1: return string else: return reverse_string(string[1:]) + string[0] s = 'Hello World' rstring = reverse_string(s) print('Original String-', s, 'Reversed String-', rstring)
Output
Original String- Python Programming Reversed String- gnimmargorP nohtyP
Using string slicing
One of the best way to reverse a string in Python is to use String slicing. In string in Python you can also use negative indexing. When negative number is used as index, String is accessed backward so -1 refers to the last character, -2 second last and so on. Thus, by providing increment_step as -1 in string slicing you can reverse a string.
def reverse_string(string): reversed = s[::-1] return reversed s = 'Hello World' rstring = reverse_string(s) print('Original String-', s, 'Reversed String-', rstring)
Output
Original String- Hello World Reversed String- dlroW olleH
Using reversed() function and join() method
In built function reversed() in Python returns a reverse iterator. Python String join() method returns a string which is created by concatenating all the elements in an iterable. By combining both of these you can get a reversed string in Python.
def reverse_string(string): rstring = "".join(reversed(string)) return rstring s = 'Python Programming' rstring = reverse_string(s) print('Original String-', s, 'Reversed String-', rstring)
Output
Original String- Python Programming Reversed String- gnimmargorP nohtyP
That's all for this topic Python Program to Reverse a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Programs Page
Related Topics
You may also like-