Practice Makes Perfect-REVERSE



Traceback (most recent call last):
File "python", line 6, in
File "python", line 5, in reverse
TypeError: string indices must be integers, not list

def reverse(str):
for i in range(len(str)):
return (str[strnew])
print reverse('abc'),


Therein find the error.

str is a function. However, it does not convert a list to a string the way one might expect.

>>> str([1,2,3,4])
'[1, 2, 3, 4]'

All it does is wrap the entire list in quotes.


Then how to convert our list to print in the correct format?


Use a function or method that does what it is supposed to. Now that we know str is not that function, we can move on. Have you learned of the join function, yet?


Not yet reached join. At this stage any other way to print?


But the SCT is expecting a return value. We don't have to print. but the return value has to be a string. If we have no way to convert our list, then it means we should be building a string that we can return. (This is fundamental stuff, not me condescending.)

Think on this and see what you come up with, for the practice. We can do a comparative exploration, then.


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