Reverse


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096#


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


#2

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.


#3

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!


#4

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

	
P
yP
tyP
htyP
ohtyP
nohtyP
!nohtyP
>>>

#5

I see. Thank you very much!


#6

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.. !?

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

#7

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

for i in text:
    rev_list.insert(i)
return rev_list

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


#8

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..


#9

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


#10

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