If you want to reverse a string in Python without using slicing, you can use a loop to iterate through the characters of the string and construct the reversed string. Here’s an example using a for loop:
def reverse_string(input_string):
reversed_string = ""
for char in input_string:
reversed_string = char + reversed_string
return reversed_string
# Example usage:
original_string = "Hello, World!"
reversed_result = reverse_string(original_string)
print("Original String:", original_string)
print("Reversed String:", reversed_result)
This reverse_string function initializes an empty string (reversed_string) and iterates through each character of the input string. It concatenates the current character with the existing reversed string, effectively building the reversed version.
Output:
Original String: Hello, World!
Reversed String: !dlroW ,olleH
This method is an alternative to using slicing ([::-1]) and provides a way to reverse a string without utilizing slice notation.