Print the given string in reverse order in Python
Understanding String Reversal
Reversing a string means changing its character order from end to start.
We will explore three different methods to reverse a string in Python.
Method 1: Using a Loop
This method iterates through the string from end to start and prints the characters.
def reverse_string(s): for i in range(len(s) - 1, -1, -1): print(s[i], end="") print() # Example usage reverse_string("hello")
Output: olleh
Method 2: Using Recursion
This method reverses the string using recursion.
def reverse_recursively(s, index): if index < 0: print() return print(s[index], end="") reverse_recursively(s, index - 1) # Example usage reverse_recursively("world", len("world") - 1)
Output: dlrow
Method 3: Using Slicing
This method uses Python's slicing technique to reverse the string.
def reverse_using_slicing(s): print(s[::-1]) # Example usage reverse_using_slicing("example")
Output: elpmaxe