Recall that a Python string can be indexed from 0 denoting the starting character to 1 less than the length of the string (denoting the ending character). Consider:
The first print statement accesses the first character of the “myname” string, i.e., K. The second print statement accesses the last character, i.e., k. Note that in the second print statement we refer to the index in relative terms, i.e., by subtracting 1 from the length of the string. The output is:
What is negative indexing?
Negative indexing allows us to access elements of a string from the end rather than from the beginning. Rather than starting at 0, we start counting from -1, -2, -3 and so on. In other words, -1 denotes the end of the string, -2 denotes the character before the end of the string, and so on.
Consider the following program:
In the first print statement, we are accessing the last character, i.e., “k”. In the second print statement which is negative one times the length of the string, we are essentially accessing the first character, i.e., “K”. The output is:
Why and when should you use negative indices?
Using negative indices can make for succinct code and can easier-to-understand code. It makes it clear that you are accessing from the end of the string rather than the beginning of the string. It is also useful when you do not know the actual length of the string. For instance, assume you are given a sentence and are trying to identify if it is an exclamation or a question or an assertion. The code for that can look like:
We are getting input from the user and testing the last character in the input and printing a suitable message. Here are sample outputs:
If you liked learning about negative indices in Python strings, learn about the usage of negative indices in Python lists.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.