Reverse a String – Python

The task is to reverse a given string without utilizing any built-in methods in Python. For instance, if the input string is “hello”, the expected output should be “olleh”. 

def reverse_string(input_string):
    reversed_string = ""
    for char in input_string:
        reversed_string = char + reversed_string
    return reversed_string

# Example usage
input_str = "hello"
output_str = reverse_string(input_str)
print(output_str)  # Output: "olleh"

In the provided code, we define a function named reverse_string that takes a single parameter, input_string.

  1. We start by initializing an empty string reversed_string which will hold the reversed characters as we iterate through the input string.
  2. We use a for loop to iterate over each character in the input_string. For each character (char), we prepend it to reversed_string. This means that the last character of the input string will be the first character of the reversed_string, effectively reversing the order.
  3. After the loop is complete, we return the reversed_string, which now contains the characters of the input string in reverse order.