Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In Python, every character within a string occupies an exact, addressable position called an index. Because strings are ordered sequences, Python provides an elegant and concise syntax to retrieve individual characters (indexing) or carve out continuous sub-segments (slicing).
Whether you are parsing file extensions from paths, extracting username handles from email addresses, or reversing sequences for cryptographic algorithms, string indexing and slicing are indispensable daily tools.
+-------------------------------------------------------------------------+
| STRING INDEXING & SLICING REAL-WORLD ANALOGY |
+-------------------------------------------------------------------------+
1. FORWARD ZERO-BASED INDEXING (Distance from the start):
- Think of a morning school assembly line.
- The first student standing at the very front is 0 steps away from
the start line -> Index 0.
- The next student is 1 step away -> Index 1.
2. REVERSE NEGATIVE INDEXING (Counting from the rear):
- The physical education teacher standing at the very back of the line:
The student at the very tail end is -1 (one step from the back).
- The second-to-last student is -2.
3. SLICING [start : stop] (Cutting a Ribbon):
- Imagine a ribbon marked with centimeter lines.
- If you make a cut at Mark 2 and another cut at Mark 5, you get
centimeters 2, 3, and 4.
- The end mark (stop) is EXCLUSIVE! You stop before cutting through 5.
+-------------------------------------------------------------------------+Understanding both positive and negative index positions across a string like "PYTHON":
To extract an individual character, place the index inside square brackets [index]:
[start:stop] FormulaSlicing extracts a substring using the pattern: $$\text{string}[\text{start} : \text{stop}]$$
start (Inclusive): The index where the slice begins (defaults to 0 if omitted).stop (Exclusive): The index where the slice ends—not included in the result! (defaults to end of string if omitted).[start:stop:step]You can provide a third parameter: $$\text{string}[\text{start} : \text{stop} : \text{step}]$$
step (Stride): Specifies the interval between characters (defaults to +1).-1) instructs Python to traverse the string in reverse!One of Python's most friendly features is that slicing never raises an IndexError, even if your indices extend far beyond the actual string boundaries!
| Task | Anti-Pattern (Don't) | Best Practice (Do) | Why |
|---|---|---|---|
| Last Character | s[len(s) - 1] | s[-1] | Negative indexing is clean, concise, and Pythonic. |
| Reverse String | Building a manual for loop | s[::-1] | [::-1] executes in optimized C bytecode in microseconds. |
| Slice to End | s[3:len(s)] | s[3:] | Omitting stop automatically runs to the very end. |
| Safe Extraction | Writing if len(s) > 10 guards for slices | Direct slice s[:10] | Slicing is naturally boundary-tolerant and never raises IndexError. |
+-------------------------------------------------------------------------+ | SLICING & INDEXING CHEAT SHEET | +-------------------------------------------------------------------------+ - First Char: s[0] - Last Char: s[-1] - Basic Slice: s[start:stop] (stop index is EXCLUSIVE!) - Omit Start: s[:n] (from index 0 up to n-1) - Omit Stop: s[n:] (from index n to the very end) - Step Interval: s[::2] (every 2nd character) - Reverse String: s[::-1] - Error Safety: s[999] -> IndexError, but s[:999] -> NO error! +-------------------------------------------------------------------------+
Python strings are immutable. You cannot assign directly to a character index:
In Python slicing text[start:stop], the stop index is exclusive (not included in the slice):
"BANGALORE"[1:5] return?A. 'BANGA' B. 'ANGA' C. 'ANGA L' D. 'BAN'
text = "Python"; print(text[20:50])?A. Python throws an IndexError: string index out of range B. Python throws a ValueError C. It executes successfully and returns an empty string "" D. Python fills the missing space with spaces
title?A. title.reverse() B. reversed(title).join() C. title[::-1] D. title[-1:0]
s = "DELHI", what character is returned by s[-2]?A. 'D' B. 'L' C. 'H' D. 'I'
"ABCDEFGH"[::3]?A. 'ADG' B. 'ACEG' C. 'ABC' D. 'CFH'
Write a complete Python script that accepts sensitive user strings (such as debit card numbers, phone numbers, and official email addresses) and uses string indexing and slicing to mask card credentials and parse corporate email domains.
In the next lesson, we will continue your Python learning journey with Modifying Strings (5: Strings).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| String Introduction | Modifying Strings |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.