Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to reverse string using lists python

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'))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading