
Python
Learn to pinpoint and extract specific characters and portions of strings using indexing and slicing.
Indexing means accessing a single character at a specific position. Python uses zero-based indexing (first character is at position 0):
word = "Python"
print(word[0]) # P
print(word[1]) # y
print(word[2]) # t
print(word[5]) # nPython allows negative indices to count backward from the end. `-1` is the last character, `-2` is second-to-last, etc.:
word = "Python"
print(word[-1]) # n (last char)
print(word[-2]) # o (second to last)
print(word[-6]) # P (first char)Slicing extracts a substring using the syntax `string[start:end:step]`. The `end` position is exclusive (not included):
sentence = "Hello World"
# Basic slicing
print(sentence[0:5]) # Hello
print(sentence[6:11]) # World
print(sentence[0:5:1]) # Hello (explicit step)
# Omitting positions
print(sentence[:5]) # Hello (from start)
print(sentence[6:]) # World (to end)
print(sentence[:]) # Hello World (entire string)The third parameter controls how many positions to skip each time:
text = "Python"
print(text[::2]) # Pto (every 2nd char)
print(text[1::2]) # yhn (starting from index 1, every 2nd)
print(text[::-1]) # nohtyP (reverse!)
numbers = "0123456789"
print(numbers[::3]) # 0369| Operation | Example | Result |
|---|---|---|
| First char | `"Hello"[0]` | `'H'` |
| Last char | `"Hello"[-1]` | `'o'` |
| First 3 chars | `"Hello"[0:3]` | `'Hel'` |
| Skip last char | `"Hello"[:-1]` | `'Hell'` |
| Every other char | `"Hello"[::2]` | `'Hlo'` |
| Reverse string | `"Hello"[::-1]` | `'olleH'` |
# Get first word from sentence
sentence = "Python is awesome"
first_word = sentence[:6] # Python
# Get last 5 characters
filename = "document.txt"
extension = filename[-4:] # .txt
# Get middle portion
code = "a1b2c3d4"
middle = code[2:6] # b2c3| Concept | Remember |
|---|---|
| Zero-based indexing | First character is at index 0, not 1 |
| Negative indices | Count backward: -1 is last, -2 is second-to-last |
| Slicing syntax | `[start:end:step]` where end is exclusive |
| Omitting values | `[:5]` starts at beginning, `[5:]` goes to end |
| Reverse slicing | Use `[::-1]` to reverse a string |
Now that you can extract parts of strings, learn string methods that transform them.
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward