Nearby lessons
62 of 159Python - String Indexing
- Understand what string indexing is and how it accesses individual characters
- Use zero-based positive indexing that starts at 0
- Use negative indexing that starts at -1
- Iterate a string using a for loop and range(len(s))
- Handle IndexError for out-of-range indexes
- Apply indexing in character extraction and password validation
What Is String Indexing?
String indexing is used to access individual characters from a string. Python supports both positive and negative indexing.
Zero-Based Indexing
Python follows zero-based indexing, so the first character starts from 0.
| Character | Positive Index | Negative Index |
|---|---|---|
| d | 0 | -5 |
| u | 1 | -4 |
| r | 2 | -3 |
| g | 3 | -2 |
| a | 4 | -1 |
Positive Indexing
Positive indexing starts from 0 and moves left to right.
Negative Indexing
Negative indexing starts from -1 and moves right to left.
Accessing First and Last Characters
Using Variables as Index
We can use variables as index values.
Index Out of Range
If index exceeds string range, IndexError occurs.
Iterating String Using Index
We can access characters one by one using a loop and indexing.
Reverse Order Traversal
We can access characters in reverse order using negative indexing.
Difference Between Positive and Negative Indexing
| Positive Indexing | Negative Indexing |
|---|---|
| Left to right | Right to left |
| Starts from 0 | Starts from -1 |
Real World Usage
String indexing is useful for character extraction, password validation, data processing, parsing text, and pattern matching.
Program to Display Characters with Positive and Negative Index
This program prints each character along with its positive and negative index, matching the Word file example.
- String indexing accesses individual characters with square brackets
- Positive indexes start at 0 and move left to right
- Negative indexes start at -1 and move right to left
- An index outside the string range raises IndexError
- Indexing can be combined with loops and variables for traversal