How to Reverse a String in Python

Reverse a String in Python: Reversing a string refers to the process of reversing the order of characters in a given string. It involves rearranging the characters from the last to the first position, resulting in a new string that is the reverse of the original string.

Examples:

Input string: “first”
Reversed String: “tsrif”

Input string: “hello world”
Reversed string: “dlrow olleh”

Problem Description

Write a Python program to reverse a given string.

Problem Solution

There are several ways to reverse a string in Python language. Let’s take a closer look at all of the methods for reversing a string in Python.

advertisement
advertisement
Method 1: Reverse a String using Slicing

In this approach, the program takes a string and use string slicing to reverse the string.

Program/Source Code

Here is source code of the Python Program to reverse a string using slicing. The program output is also shown below.

a=str(input("Enter a string: "))
print("Reverse of the string is: ")
print(a[::-1])
Program Explanation

1. User must enter a string.
2. By giving the increment value as -1, string slicing is used to reverse the list.
3. The reversed string is printed.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Time Complexity: O(n)
The time complexity for the given code is O(n), where n is the length of the input string. The slicing operation a[::-1] takes linear time complexity.

Space Complexity: O(n)
The space complexity is O(n) as well. The reversed string is stored in a new string object of length n.

Runtime Test Cases

Testcase 1: In this case, the string “hello” is entered as input to reverse the string.

Enter a string: hello
Reverse of the string is: 
olleh

Testcase 2: In this case, the string “test” is entered as input to reverse the string.

advertisement
Enter a string: test
Reverse of the string is: 
tset

Method 2: Reverse a String using Recursion

In this approach, we use recursion to reverse a string by repeatedly swapping the first and last characters.

Program/Source Code

Here is source code of the Python Program to reverse a string using recursion. The program output is also shown below.

def reverse(string):
    if len(string) == 0:
        return string
    else:
        return reverse(string[1:]) + string[0]
a = str(input("Enter the string to be reversed: "))
print(reverse(a))
Program Explanation

1. User must enter a string.
2. The string is passed as an argument to a recursive function to reverse the string.
3. In the function, the base condition is that if the length of the string is equal to 0, the string is returned.
4. If not equal to 0, the reverse function is recursively called to slice the part of the string except the first character and concatenate the first character to the end of the sliced string.
5. The reversed string is printed.

advertisement

Time Complexity: O(n)
The time complexity of this recursive approach is O(n), where n is the length of the string. Each recursive call takes constant time, and the number of recursive calls is equal to the length of the string.

Space Complexity: O(n)
The space complexity is also O(n) due to the recursive calls and the memory used for the string concatenation.

Runtime Test Cases

Testcase 1: In this case, the string “hello world” is entered as input to reverse the string.

Enter the string to be reversed: hello world
dlrow olleh

Testcase 2: In this case, the string “first” is entered as input to reverse the string.

Enter the string to be reversed: first
tsrif

Method 3: Reverse a String using Loops

In this approach, we use for loop to reverse a string by repeatedly swapping the first and last characters.

Program/Source Code

Here is source code of the Python Program to reverse a string using loops. The program output is also shown below.

def reverse_string_loop(string):
    reversed_string = ''
    for char in string:
        reversed_string = char + reversed_string
    return reversed_string
 
string = input("Enter the string to be reversed: ")
print(reverse_string_loop(string))
Program Explanation

1. The function reverse_string_loop takes a string as input and initializes an empty string reversed_string to store the reversed string.
2. It uses a loop to iterate over each character in the input string.
3. Inside the loop, it concatenates each character with the reversed_string, but in reverse order.
4. After the loop, it returns the reversed_string.
5. The program prompts the user to enter a string to be reversed using the input() function and assigns it to the variable string.
6. Finally, it calls the reverse_string_loop function with the string as an argument and prints the reversed string using print().

Time Complexity: O(n)
The time complexity of the program is O(n), where n is the length of the input string. This is because the program iterates through each character in the string once.

Space Complexity: O(n)
The space complexity of the program is O(n), as it creates a new string of the same length as the input string to store the reversed string.

Program Output:

In this case, the string “hello world” is entered as input to reverse the string.

Enter the string to be reversed: hello world
dlrow olleh

To practice programs on every topic in Python, please visit “Programming Examples in Python”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.