# How can I loop through text starting from the last character?

#1

## Question

How can I loop through text starting from the last character?

### With a For loop

Recall that `range()` has three different ways to use it, and one of them is `range(start, end, step)`, which is one possible way to solve this problem.
We know we want to `start` at the end, but be careful to subtract 1 from the length of the input string, `text`, otherwise you’ll get an out of bounds error because counting starts from 0!
Then we continue until -1 because it will `stop` at 0 since it’s exclusive.
And each time we want to `step` down by 1.
Inside the loop we can access parts of the string like we would a list, where we write `string_name[index]`. Using this character we accessed, we can add it to our new reversed version of the string and we’ll solve the problem!
This is, of course, just one approach, and you may very well find a better one or one you prefer!

### With String Indices

Using string indices, you can walk backwards through a string like this:

``````foo = "example text"
foo[::-1]
# prints: 'txet elpmaxe'
``````

FAQ: Learn Python - Practice Makes Perfect - reverse
#2

Not clear enough! Does “step” -1 makes it count from last character to first?

#3

#5

Nope, the whole construction may do it. I mean, if you get a range() function, you have three parameters:
first the start point
second the end point
third how many steps (forward or backward) you want to take.

So if you want to go from 0 to 3, 1 by 1: range (0, 4, 1), but if you want to go from 3 to 0 1 by 1: range(3, -1 (as it has to take 0 and this last is exclusive), -1)

I hope it helps.

Bye

#6

Great explanation @capitanpaella! Thank you so much!

#7

i used this code to reverse the text but i am confused as to how the `for loop` is able to reverse the text logically. Can someone explain to me please.

``````def reverse(text):
rev = ""
for i in text:
rev = i + rev
return rev
``````

#8

its not, but you prepend/insert at the beginning of the string, which is causing the reverse process:

``````def reverse(text):
rev = ""
for i in text:
rev = i + rev
print rev
return rev

print reverse("hello")
``````

#9

still not clear with the explanation above

#10

Given a word, “Python”,

``````for i in word:
``````

The first letter of the word will be “P”, so `rev` will look like,

``````P
``````

The second letter will be `y` which when concatenated to the front of the `rev` string will look like,

``````yP
``````

Notice how `i` prepends the string? Next the ‘t’…

``````tyP
``````

Starting to make sense?

#11

i now get it
thank you very much

#12

A post was split to a new topic: Index errror trying to reverse string

#13

So I’ve tried the following code and it gives me nothing in output:

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

reverse(‘Hello’)

any ideas why?
p.s even if I do print reverse (“Hello”) it still gives me nothing. Does let not work inside a range function?

#14

When using a range that starts from the highest value, be sure to give it a negative direction.

``````range(x - 1, -1, -1)
``````

The first argument points to the last index of the string.

The second argument points to the first non-iterated index. Since the direction is right to left, we set this to -1 so that 0 doesn’t get skipped.

The third argument is the direction and step. Negative means move right to left, 1 is the stride length.

#15

ok thank you @mtf I get this part, but how I can change it so it will print the actual letters, i.e. the reversed version of “Hello”
I tried
for i in text[len(text): -1 : -1]:
print (i)
but it again gives me nothing

#16

Be sure that stop and step are both negative 1, and remember to subtract 1 from the length so you get the last index as your start. The `range` approach is the handiest at getting the indices.

A cheat approach (not really cheating, but over-simple) is the reverse slice…

``````text[::-1]
``````

however that doesn’t really teach us anything or let us build up our experience and understanding of working with ranges and indexes.

#17

Yes, I agree, that’s why I am trying approach with range, but it does not work. If you look at my code it says
def reverse(text):
for i in text[len(text)-1:-1:-1]:
print (i)

reverse(“Hello”)

so I do have negative 1 for stop and step, and I am subtracting 1 from length of the input, however still my output is empty.
If I use range, as in my initial question I get only numbers, but not letters

#18
``````>>> text = "hello"
>>> text[len(text)-1, -1, -1]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
text[len(text)-1, -1, -1]
TypeError: string indices must be integers
>>>
``````

Use the range to get at the indices.

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

Study the range…

``````>>> print (list(range(10, -1, -1)))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>>
``````

Then access the index, `text[i]`.

``````>>> for i in range(len(text) - 1, -1, -1):
print (text[i], end='')

olleh
>>>
``````

That covers printing in the function, but what if you want to return a string and print the return value.

#21