I found this piece of code from a related question about reversing strings in python, but can someone please interpret it in plain English? Please note that I am still new to python and only learnt how to use while loops and functions yesterday :/ so I cant really put this into words myself cause my understanding isn’t quite there yet.
anyways here is the code:
def reverse_string(string): new_strings =  index = len(string) while index: index -= 1 new_strings.append(string[index]) return ''.join(new_strings) print(reverse_string('hello'))
Surely by knowing what it does, you can figure the code. In the
while loop, the
index value starts from the end of the string and counts down to 0. In each step, it adds that character (again, starting from the end) to the end of the list it is building. Finally, it combines the list into a string.
So, given ‘abcd’, the list gets built:
'abcd' #3 -> ['d'] 'abcd' #2 -> ['d','c'] 'abcd' #1 -> ['d','c','b'] 'abcd' #0 -> ['d','c','b','a']