It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Indices

Understanding String Indices in Python

In Python, indices (or index values) allow us to access individual characters within a string. Each character in a string has a corresponding index, starting from 0 for the first character and counting up from there.

Zero-Based Indexing

Python uses zero-based indexing, which means the first character of a string is at index 0, the second character is at index 1, and so on.

word = "Python"
print(word[0])  # Output: P
print(word[1])  # Output: y
print(word[5])  # Output: n

Negative Indexing

Python also supports negative indexing, where -1 refers to the last character, -2 refers to the second-last character, and so on.

word = "Python"
print(word[-1])  # Output: n
print(word[-2])  # Output: o
print(word[-6])  # Output: P

Accessing Characters in Strings

To access a character at a specific index, you use square brackets ([]).

text = "Hello, World!"
print(text[7])   # Output: W
print(text[-5])  # Output: o

Out-of-Range Index

If you try to access an index that doesn’t exist in the string, Python will raise an IndexError.

text = "Python"
print(text[10])  # IndexError: string index out of range

Iterating Over String Indices

You can use a for loop and the range() function to iterate over a string by index.

word = "Python"
for i in range(len(word)):
    print(f"Index {i}: {word[i]}")

Exercise: Try It Yourself!

  1. Create a string variable language and store the value "Programming" in it. Print the first and last letter using indices.
  2. Try accessing an index that does not exist in the string and observe the error message.
  3. Print each character of the string "Python" using both positive and negative indice.