Practice Makes Perfect-REVERSE


#1

WHAT IS WRONG ?

ERROR:
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):
strnew=[]
for i in range(len(str)):
strnew.append(str[len(str)-i-1])
return (str[strnew])
print reverse('abc'),


#2

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.


#3

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


#4

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?


#5

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


#6

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.


#7

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