Reverse


#1

7.reverse

Why code below gives me 198765432, but if I do new_word.append(text[-i-1]), it gives me correct 987654321, can’t get this.



def reverse(text):
  new_word = []
  for i in range(len(text)):
    new_word.append(text[-i])
  return ''.join(new_word)
  
print reverse("123456789")


#2

Hi @blonpina,

A negative index accesses a sequence from the end of the sequence. For example, an index of -1 refers to the final element in the sequence, and an index of -2 refers to the second-to-last element.

Consider how you can use len(text) as part of the index computation in this line to access text, instead of using simply -i

    new_word.append(text[-i])

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.