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
.
- We start by initializing an empty string
reversed_string
which will hold the reversed characters as we iterate through the input string. - We use a
for
loop to iterate over each character in theinput_string
. For each character (char
), we prepend it toreversed_string
. This means that the last character of the input string will be the first character of thereversed_string
, effectively reversing the order. - After the loop is complete, we return the
reversed_string
, which now contains the characters of the input string in reverse order.