0

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'))
5
  • Why anyone would use that mess instead of ''.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. Commented Nov 24, 2021 at 4:12
  • @Grismar have you noted that OP is begineer and have knowledge till while loop in python? Commented Nov 24, 2021 at 4:21
  • @Grismar: You shouldn't call this example code for/from a beginner "a mess" if you're overcomplicating it yourself. You don't need the call to list, so ''.join(reversed(my_string)) is enough. But of course my_string[::-1] is even better. Commented Nov 24, 2021 at 8:50
  • @Matthias - I meant no offense, the question seems to suggest this code was not authored by OP ("found this piece of code") but provided to them and they were having trouble understanding it. If that's not the case and OP wrote it themselves, they have my apologies. It doesn't change my opinion of the code, but I agree with you that from the hands of an inexperienced coder, code that does what it says on the tin is a good start and worthy of encouragement. I think the opinion of experienced coders (when paired with a usable suggestion for improvement, which I provided) can be helpful. Commented Nov 24, 2021 at 21:43
  • @Matthias - I fully agree with your suggested improvements by the way. I didn't write an answer, but I'd like to think I would have included your first suggestion with some explanation. The reason I didn't was to stay closer to the proposed solution with more pythonic code. I hadn't yet thought of your second suggestion and am not sure I agree that [::-1] is really better than reversed() in this case. Shorter does not equal better, so it would have to be down to performance (maybe) or readability (definitely not). Commented Nov 24, 2021 at 21:45

3 Answers 3

4

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']
Sign up to request clarification or add additional context in comments.

Comments

1

Well basically, the get the length of the string with the len method. Which will return you an integer value representing how long that string is.

They then use the length of this string and effectively iterate down to zero in a while loop. Using the -= operator.

Each iteration (meaning each time around the loop) it will take away from length until it reaches zero.

So lets use hello as an example input and go through this together.

reverse_string('hello') is how we would call the method, done in the print statement of your code.

We then enter the function and perform these steps:

  1. We create a new empty array called new_strings.
  2. We find the length of the initial string hello which returns us 5. Meaning that now index is equal to 5.
  3. We create a while loop that keeps on going until index is no more using while(index): - a while loop like this treats a 0 value as falsy and will terminate upon reaching this. Therefore when index is 0 the loop will stop.
  4. The first line of this loop performs index -= 1 which is the same as writing index = index - 1 so the very first loop through we get index = 5 - 1 and then now index is equal to 4.
  5. Because Python then lets us access the character of a string using string[index] (and because this works from 0 -> n) performing hello[4] will in fact give us the character o.
  6. We also append this character to the array new_strings meaning that as we go through the iterations to reach zero it will add each character backwards to this array giving us ['o', 'l', 'l', 'e', 'h']
  7. Since index is now zero we leave the loop and perform a join operation on the array to yet again create a string. The command ''.join(new_strings) means that we wish to join the array we previously had without a separator. If we had done '#'.join(new_strings) we instead would have gotten o#l#l#e#h instead of olleh.

I hope this answer gives you some clarity.

3 Comments

ah this clarifies my questions bout that last line which i was about to ask. Thanks for the explanation :)
No worries at all. I'm glad I could be of service. Tim Roberts is right though; many of these things can be understood by going through the fundamentals. I suggest that whenever you stumble upon code you don't understand, try lookup the language documentation for the method/operator. Even if you don't understand it in the beginning, getting into the habit of this and trying to understand it will serve you very well moving forward.
As an example str.join() documentation which is part of the Python built-in types documentation can prove to be very very useful later on but I can understand how it will seem overwhelming and confusing at this point, but it is very good to get into the habit of finding these resources and learning how to interpret them.
0

Sure, It is very simple program. You should reffer string methods and string indexing in python to get clear idea. Let me explain this in deatial.

print(reverse_string('hello'))//The print function is calling another function reverse_string and passing argument"hello".

def reverse_string(string):// The argument "hello" is stored in the variable string in reverse_string function.

**new_strings = []** // created a new empty list
**index = len(string)** // len function returns the length of the argument 
                           passed to the function. len("hello")=5 and assigned 
                           to index. index=5.

while index: // while loop exicute until the condition get false .In this example when index =0.in string the indexing start from 0 .For example. string[0]=h,string[1]=e,string[2]=l,string[3]=l,string[4]=o.

    **index -= 1**  //Note the last letter 'o' is in string[4] and the len 
                      function returned 5 so we need to decrement index variable 
                      to 4 so that it will pointing to string[4]=o                     
  

new_strings.append(string[index]) // append string[4] that is o and so on ... return ''.join(new_strings)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.