# Reverse

#1

reverse

Oops, try again. Your function fails on reverse("Python!"). It returns " !nohtyP" when it should return "!nohtyP".

uhhhhh. what? Im right but I am wrong?

``````def reverse(text):
result = " "
i = len(text)
while i > 0:
result += text[i-1]
i -= 1
return result

reverse("Python!")``````

#2

If you look at the output you will find there is an extra space.
This extra space is created because you defined/initialized your `result` string with one space character.

#3

I got everything except... why does your code prints the last letter as well ( in result as the first one)? or in other words why is it:

and not: result += text[i]?

Does it start at zero and that is why i-1 is the last letter? Would be great if someone could confirm or explain it again?

#4

Yes,strings are 0 indexed so when we were trying add letter in reverse ,we started from last character's index that is `len(string) - 1`.

Strings are 0-indexed.

what does that mean?

suppose.. `x` is a string.

`x = "abcdefg"`

``````at index 0 -- > 'a'
at index 1 -- > 'b'
at index 2 -- > 'c'
at index 3 -- > 'd'
at index 4 -- > 'e'
at index 5 -- > 'f'
at index 6 -- > 'g'``````

You can see python counts from 0 unlike us humans.
One cool thing to note, You can also find characters using negative indices.

last character will have index of -1 (Right to Left)

``````at index -7 ---> 'a'
at index -6 ---> 'b'
at index -5 ---> 'c'
at index -4 ---> 'd'
at index -3 ---> 'e'
at index -2 ---> 'f'
at index -1 ---> 'g'``````

#5

I have a similar set up:
def reverse(text):
result = " "
stuff = len(text)
while stuff > 0:
result += text[stuff-1]
stuff -= 1
return result

reverse("giraffe")

It comes up as an infinite loop?

#6

def reverse(text):
result = "" # close the parentheses
stuff = len(text)
while stuff > 0:
result += text[stuff-1]
stuff -= 1
return result

#7

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