Python Basics - 10. Strings, Slicing, and Unpacking

Strings and sequence operations are used everywhere in Python. This notebook covers indexing, slicing, formatting, unpacking, and useful built-in sequence helpers.

Download Notebook

Download this notebook

1. Indexing and Slicing

Python uses zero-based indexing. Negative indices count from the end.

text = "Python Language"
print(text[0])
print(text[-1])
print(text[0:6])
print(text[7:])
print(text[::-1])  # Reverse string
P
e
Python
Language
egaugnaL nohtyP

2. String Formatting

f-strings are the modern and readable way to format output.

name = "Alice"
score = 93.4567
print(f"Student: {name}, score: {score:.2f}")
print(f"Binary of 10 is {10:b}, hex is {10:x}")
Student: Alice, score: 93.46
Binary of 10 is 1010, hex is a

3. Sequence Unpacking

Unpacking assigns elements from a sequence into multiple variables in one statement.

point = (10, 20)
x, y = point
print(f"x={x}, y={y}")

numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(first, middle, last)
x=10, y=20
1 [2, 3, 4] 5

4. zip, enumerate, and sorted

These helpers are frequently used in clean Python code.

names = ["Alice", "Bob", "Cara"]
scores = [90, 85, 95]

for idx, (name, score) in enumerate(zip(names, scores), start=1):
    print(f"{idx}. {name}: {score}")

print(sorted(names, reverse=True))
1. Alice: 90
2. Bob: 85
3. Cara: 95
['Cara', 'Bob', 'Alice']