7. Reverse - how to use .join


#1

Ok, so I solved the problem with a different code, but below is the code I failed with.
I cannot join the letters in the list together. How can I join them together using .join?

def reverse(text):
    product = []
    for i in range(len(text)-1,-1,-1):
        product.append(text[i])
    " ".join(product)  
    return product

#2

you can store the result of the join into a variable:

product = " ".join(product)

or return it directly:

return " ".join(product)

you where so close


#3

Could you explain what this does? I'm not sure I understand what's happening:

for i in range(len(text)-1,-1,-1):


#4

range has 3 values:
range(start,stop,step)

strings are zero indexed based, while length start counting at one, so the last character is is indexed at length -1 (range start value), range does not include the stop value so you need -1 to get the character at index 0. and you want to loop from high to low so the steps needs to be -1


#5

Thanks. I'm still getting my head wrapped around it but that helps. I was assuming that the process steps up from low to high.


Reverse
#6

there is one simply way to find get good insight:

x = "hello"
for i in range(len(x)-1, -1, -1):
   print i, x[i]

see what the loop does by adding print statements


#9

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