Kodeclik Blog


Negative Indexing in a Python String

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.
If you enjoyed this blogpost about negative indices in strings, learn negative indices in Python lists.
For more Python content, checkout the math.ceil() and math.floor() functions! Also learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.