7. Reversed. Not where to from here



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

This is obviously some kind of glitch. Can anyone help me solve this issue?

def reverse(text):
    result = ' '
    for i in text:
        result = i + result
    return result


you initially set result to ' '

that means your actual result is
'!nohtyP '
^ note the empty space.

That's what this looks like from my angle.

so result = ''


Oh silly me! Did not spot that at all. Removing the space solved the issue.

Thank you so much for your time.


def reverse(text):
rev = ' '
length = len(text)
for index in range(len):
rev = rev + text[len - (index + 1)] #index starts from 0
return rev



what does setting something equal to "" do? i must have forgotten or something


We do it to store in an empty string. In my code above, the variable 'get filled' in the loop. Sorry I'm not the best at explaining things.


Is there a reason that i'm missing for why does the line ''result = i + result'' reads backwards while 'result = result + i' would read it normally? Shouldn't the second one remain the same as it is now while the first one just print 'Python! ' with the space at the end?


Noob here. At first glance it does seem that way, I had the same problem. If you test a short word in your head, it makes sense. Let's use pig.
so result is first empty, so the first iteration will put in the "p" into our string.
result = p
the next iteration will take the "i""
result = "i" + "p" = "ip"
result = "g" + "ip" = "gip"

if you changed it to result = "result" + "i" you would get "pig" back instead.

I don't really understand the other solution mentioned here in the forums, but this solution is super elegant and simple. And for whatever reason the setup mixes up the brain so it doesn't seem to come to someone right away.


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