def reverse(x):
output = ""
for c in x:
output = c + output
return output
print(reverse("Hello"))
This code works fine to reverse a string in Python, I just can't seem to understand why it is working and how.
If, for example, I iterate through a string, usually it will iterate and print starting from "H" and work its way down to "O." How is it that here, it's going backwards?
output = c + output. The character is concatenated to the beginning of the output string instead of to the end, resulting in a reversed string. The easiest way to reverse a string, however, isx[::-1].