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"
Another efficient way to reverse a string in Python is by using slicing. Here is a simple and efficient way to do it –
# Original string
original_string = "Hello, World!"
# Reversed string using slicing
reversed_string = original_string[::-1]
print(reversed_string)
This method uses Python’s slicing feature, where [::-1] means “take the string and step backward by 1.” It’s concise and performs very well.