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!
- Create a string variable
language
and store the value "Programming" in it. Print the first and last letter using indices. - Try accessing an index that does not exist in the string and observe the error message.
- Print each character of the string "Python" using both positive and negative indice.