How can I loop through text starting from the last character?
With a For loop
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