7. reverse


These exercises are challenging and satisfying when you get them. But, this one is stumping me. When I've looked at previous posts on this lesson, all the posts have significantly more lines than I do. I hope I'm not missing that much, because I believe that i = len(text) - i is doing what I need to perfectly. I just need a bit of help here.

Oops, try again. Does your reverse function take exactly one argument (a string)? Your code threw a "unsupported operand type(s) for -: 'int' and 'str'" error.

The console says "None" and when I tell it to print reverse("Python!") it reads:
Traceback (most recent call last):
File "python", line 6, in
File "python", line 4, in reverse
TypeError: unsupported operand type(s) for -: 'int' and 'str'

def reverse(text):
    new_string = str(text)
    for i in new_string:
        i = len(text) - i
    return new_string


Strings aren't mutable, they can't be changed
i is also not part of the string, even if the string was mutable

Without "cheating" and just have python reverse it, you should be using a list to do the changes and then concatenate the characters into a single string with


'' is the delimiter, in this case empty cause you wouldn't want them comma separated or anything such

It's also possible to just repeatedly use + on two strings to concatenate them, but you would create an entirely new string each time. For short strings this is insignificant, but it's important to have a grip on what's being done at all times.


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