Kodeclik Logo

Our Programs

Courses

Gifting

Learn More

Schedule

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:

myname = "Kodeclik"
print(myname[0])
print(myname[len(myname)-1])

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:

K
k

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.

What is the first negative index in a Python string

Consider the following program:

myname = "Kodeclik"
print(myname[-1])
print(myname[-len(myname)])

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:

k
K

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:

user_input = input("Please enter a sentence: ")

if (user_input[-1] == "?"):
  print("You entered a question.")
elif (user_input[-1] == "!"):
    print("You entered an exclamation.")
else:
      print("You entered an ordinary sentence.")

We are getting input from the user and testing the last character in the input and printing a suitable message. Here are sample outputs:

Please enter a sentence: It is raining!
You entered an exclamation.

Please enter a sentence: How are you?
You entered a question.

Please enter a sentence: The sky is blue.
You entered an ordinary sentence.

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.

Kodeclik sidebar newsletter

Join our mailing list

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

About

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.

Copyright @ Kodeclik 2024. All rights reserved.