- Read Tutorial
- Watch Guide Video
In review, the first value here is zero. The next one is one and it counts all the way up in successive values. However, if you want to get to the very back and you actually want to work backwards then we can work with negative index values and so that's what our guide is going to be about here. So say that we want to grab simply the very last character from the string. What I can do is if I come down to sentence here I can grab a slice of the sentence by simply passing in a negative one.
So now if I print this out you can see it has the period there
If I want to go back even further I can say -3 and it's going to print out the "o" from "dog" and we could just keep going and grab our values in this negative index kind of manner that is helpful. But that will only allow us to grab a single value. So what if we want to be able to grab the last word here? And we now say that we're in a situation where we know that every last word in this sentence or what we have here and what we have to work with is going to contain four characters.
What we can do is still work with our range. So I can say -4: and then just leave the rest blank.
sentence = 'The quick brown fox jumped over the lazy dog.' print(sentence[-4:])
Part of the reason why I wanted to include this guide in the course was to give a little bit more of a refresher on how to work with ranges because this is going to be a very important topic when we get into machine learning and concepts like that.
If you remember whenever we pass in a colon and we leave the rest of the argument blank then it's going to go to the very end of the string. So if this works this should print out "dog" with the period at the very end. After running this you can see that is exactly what we get.
So in review, this is how you can work with negative indices inside of a python string.
Code
sentence = 'The quick brown fox jumped over the lazy dog.' print(sentence[-4:])