Nearby lessons
57 of 108Python - String Indexing
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.
main.py
p y t
Negative Indexing
Negative indexing starts from -1 and moves right to left.
main.py
n o h
Accessing First and Last Characters
main.py
First Character: d Last Character: a
Using Variables as Index
We can use variables as index values.
main.py
h
Index Out of Range
If index exceeds string range, IndexError occurs.
main.py
IndexError: string index out of range
Iterating String Using Index
We can access characters one by one using a loop and indexing.
main.py
python
Reverse Order Traversal
We can access characters in reverse order using negative indexing.
main.py
nohtyp
Difference Between Positive and Negative Indexing
| Positive Indexing | Negative Indexing |
|---|---|
| Left to right | Right to left |
| Starts from 0 | Starts from -1 |
main.py
p p
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.
main.py
Enter Some String:durga The character present at positive index 0 and at negative index -5 is d The character present at positive index 1 and at negative index -4 is u The character present at positive index 2 and at negative index -3 is r The character present at positive index 3 and at negative index -2 is g The character present at positive index 4 and at negative index -1 is a
Sample Output:
Important Points
- String indexing starts from
0in the forward direction. - Negative indexing starts from
-1in the backward direction. - Every character in a string has both a positive index and a negative index.
- Invalid indexes raise an
IndexError.
Summary
| Feature | Description |
|---|---|
| Positive Index | Left to right |
| Negative Index | Right to left |
| First Positive Index | 0 |
| First Negative Index | -1 |
| Error for Invalid Index | IndexError |