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'))
''.join(reversed(list(my_string)))I don't know, but what part of it don't you understand? It creates an empty list, then very inefficiently loops over the string from the end to the start, adding each character to the list, and finally joining the characters in the list together in a string and returning the result.whileloop in python?list, so''.join(reversed(my_string))is enough. But of coursemy_string[::-1]is even better.[::-1]is really better thanreversed()in this case. Shorter does not equal better, so it would have to be down to performance (maybe) or readability (definitely not).