0

I'm learning python and the "teacher" (a youtube channel) gives this function to revert the characters of a given array. I can't understand how the function reverts the characters.

1    alfa = "hello"
2    def reverser(string):
3        index = (len(string) -1) 
4        new_string = ""
5        while index >= 0:
6            new_string += string[index]
7            index -= 1
8        print(new_string)
9    
10    reverser(alfa)

Line 3: I know len returns the number of "hello" in this case. That -1 confuses me. Is it used to return the last character or to subtract the LEN result? why?

Line 4: ok we are creating a new string.

Line 6: No ideas...

Line 7: No ideas again...

I need help to understand it.

2
  • Welcome to SO Mauro. Thanks for taking the time to write your understanding of the code. I hope you stick with learning Python Commented Dec 20, 2018 at 18:09
  • If David the third's answer is satisfactory and worked for you be she to give him the green checkmark next to his answer. Commented Dec 20, 2018 at 18:56

1 Answer 1

1

Line 3: You are getting the length of string and subtracting 1 from it. The reason for this is the way indexing works in python. When using indexing in python, the first element is at position 0, and len returns the length of the string. Subtracting one from it makes it consistent with the way indexing works.

Line 6: You are appending the character in string at index to new_string.

Line 7: index will be decremented by one, meaning it's value will be one less than before in order to use the character before the last one used in the string.

Sign up to request clarification or add additional context in comments.

2 Comments

It may be worth explaining why we subtract 1 from the length of string. As taking the len starts counting at 1 but in coding we use zero indexing - so the 5th letter is indexed as 4.
Thanks for the super fast answer! So in the loop it start reading the characters from the last one (given by the len) and subtracting 1 by 1 until the loop is not True anymore. Right?

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.