Reverse """Can someone explain how it works ?"""


#1


So , with help of 3 codes from internet i made this one , it works perfect and it let me pass further but i don't fully understand third line of the code

Why if i write him in such a way :

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

It will loop in such a way that it will give me all characters except last one, in my case the "n"

The actual code


def reverse(text):
    output = []
    for i in range(len(text)-1, -1, -1):
        output.append(text[i])
    rev = str(output)
    g = ''
    for f in output:
        g = g + f
    return g

reverse("abcdefghmn")


#2

this code:

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

it won't give you the last value letter, because you subtract one?

if you have the following string:

"hello"

we have a length of 5, so indexes: 0, 1, 2, 3 and 4. range does include its stop value, so in this case that is good:

text = "hello"
for i in range(len(text)):
   print i, text[i]

if you then also subtract one, you don't get the last letter


#3

Ok , i got the ideia , but why if i replace

for i in range(len(text)):

with

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

It gives me the reversed word ...
how this range(len()) structure works ?

start,stop,step how it works in this case with len() inside ?


#4

range can have:

start,stop,step

so in this example:

range(len(text)-1, -1, -1):

len(text) - 1 is the start value, -1 is the stop value, and -1 is the step value


#5

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