Python Program to Reverse a String

Reversing a string is one of the most common beginner problems in Python. It helps in understanding indexing, slicing, and loops.

In this tutorial, we will explore multiple methods to reverse a string efficiently.

1. Understanding the Problem

Given a string, reverse it.

Input: hello
Output: olleh

2. Method 1: Using Slicing

Python
string = input("Enter a string: ")

reversed_string = string[::-1]
print(reversed_string)

Slicing is the most Pythonic and efficient way to reverse a string.

3. Method 2: Using For Loop

Python
string = input()
reversed_string = ""

for char in string:
    reversed_string = char + reversed_string

print(reversed_string)

This method builds the reversed string manually.

4. Method 3: Using While Loop

Python
string = input()
reversed_string = ""
i = len(string) - 1

while i >= 0:
    reversed_string += string[i]
    i -= 1

print(reversed_string)

This method uses indexing to reverse the string.

5. Method 4: Using Function

Python
def reverse_string(s):
    return s[::-1]

print(reverse_string("Python"))

Functions make your code reusable and clean.

6. Method 5: Using reversed()

Python
string = input()

reversed_string = ''.join(reversed(string))
print(reversed_string)

The reversed() function returns an iterator, which is joined into a string.

7. Algorithm

1. Take input string.

2. Traverse string in reverse order.

3. Store characters in new string.

4. Print reversed string.

8. Common Mistakes

1. Incorrect slicing syntax.

2. Forgetting string immutability.

3. Using wrong loop logic.

4. Not initializing empty string.

9. Applications

1. Palindrome checking.

2. Text processing.

3. Data transformation.

4. Algorithm practice.

Conclusion

Reversing a string is a fundamental problem that helps you understand Python string operations deeply.

Using slicing is the most efficient approach, but practicing other methods strengthens your logic.