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'

You can read more about this method here: https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3


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

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


#3

[Edit - I’ve moved this post into the main one, above. Please read it instead.]


#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