1. Introduction to String Indexing in Python
In Python, a string is an ordered sequence of characters, each uniquely identified by a Unicode value.
This means every character in a string — from the first to the last — has a fixed position (index).
Python uses zero-based indexing, where:
- The first character is at position 0.
- The second is at position 1.
- And so on, up to the final character.
Let’s visualize an example:
| Character | H | E | L | L | O | | W | O | R | L | D | | ——— | – | – | – | – | – | – | – | – | – | – | — | | Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
In short:
Each letter of “HELLO WORLD” can be accessed using its index number.
2. Accessing Characters in a String Using Index
Python allows direct access to individual characters by placing the index number inside square brackets [ ] after the string variable name.
text = "HELLO WORLD"
print(text[0]) # First character
print(text[7]) # Eighth character
print(text[10]) # Last character
#Output
H
O
D
Explanation:
- text[0] → returns the first character ‘H’.
- text[7] → returns ‘O’.
- text[10] → returns ‘D’, the last character.
Note:
If you try to access an index that doesn’t exist (e.g., text[20]), Python raises an IndexError.
3. Understanding Negative Indexing in Python
Python also supports negative indexing, allowing access to characters from the end of the string.
Here, indexing starts from -1 (the last character) and decreases leftward.
Let’s visualize this again:
| Character | H | E | L | L | O | | W | O | R | L | D |
| ————– | — | — | — | — | — | — | — | — | — | — | — |
| Negative Index | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
phrase = "HELLO WORLD"
print(phrase[-1]) # Last character
print(phrase[-5]) # Fifth from the end
print(phrase[-11]) # First character
#Output
D
W
H
Explanation: Negative indexing is a convenient way to access elements starting from the end, especially when you don’t know the exact length of the string.
IndexError:
If the negative index exceeds the string’s length, Python raises:
IndexError: string index out of range
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.