In my first attempt I wrote the Line 4 as 'word += str(i)' and it didn't work. After I changed it to 'word = str(i) + word', it worked. I don't think I understand what these two different codes do differently. Could you please explain it to me? How come one worked and the other not?

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


i is already a string, so no str() needed. What the above code is doing is building an identical string to the original text. Your second approach works because it builds the new string from the left side, not the right. Likewise, str() is not needed.


Could you please elaborate how word = i + word will build the new string from the left side? Could you please provide me an example? Thanks!


>>> word = 'Python!'
>>> rev_word = ''
>>> for letter in word:
	rev_word = letter + rev_word
	print (rev_word)



I see. Thank you very much!


Your way is way more practical, but how about this one and why doesnt it work!? It gives again an Oops message with a garbage of the return value of my function:(
I am interested in the use of this way.. its logic looks ok but.. !?

def reverse(text):
    for i in text:
        reverse_list.insert(countback-1, i)
    return str(reverse_list)


Not needed. You are only viewing the letters in text. Their positions are unimportant.

for i in text:
return rev_list

We only need to supply a second positional argument when the insert position is not 0.


Oh just saw your reply, thank you:) but then doesnt it - .insert(i) - place from the first position of the list to the last? Which means appending it.. which actually means to write the same characters in the variable "text" in the same order to the list?
I am really confused..


The insertion point is always index 0 if none is specified in the second (optional) argument.


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