Unit 11.3A · Term 3

Advanced String & List Methods

Beyond the basics, Python provides advanced methods for sophisticated text processing and list manipulation. Mastering these methods lets you write cleaner, more efficient code for complex problems.

Learning Objectives

  • 11.3.1.1 Use advanced string methods to solve problems
  • 11.3.1.2 Use advanced list methods to solve problems

Lesson Presentation

11.3A-lesson-16-advanced-methods.pdf · Slides for classroom use

Conceptual Anchor

The Power Tools Analogy

If basic methods are hand tools, advanced methods are power tools. enumerate() is a nail gun (fast indexing), zip() is a clamp (holding two things together), and map()/filter() are assembly-line machines that process items in bulk.

Rules & Theory

Advanced String Techniques

# ord() and chr() — character ↔ ASCII code print(ord('A')) # 65 print(ord('a')) # 97 print(chr(65)) # 'A' print(chr(97)) # 'a' # Caesar cipher shift char = 'D' shifted = chr(ord(char) + 3) # 'G' # String formatting with f-strings (advanced) name = "Ali" score = 95.5 print(f"{name:>10}") # " Ali" — right-align, width 10 print(f"{score:.1f}") # "95.5" — 1 decimal place print(f"{score:06.2f}") # "095.50" — pad with zeros print(f"{42:b}") # "101010" — binary print(f"{255:x}") # "ff" — hexadecimal # .center(), .ljust(), .rjust() print("Title".center(20, "=")) # "=======Title========" print("Name".ljust(15, ".")) # "Name..........." print("99".rjust(5, "0")) # "00099" # .zfill() print("42".zfill(5)) # "00042" # .partition() s = "name=Ali" before, sep, after = s.partition("=") print(before, after) # "name" "Ali"

Advanced List Techniques

# enumerate() — get index + value together fruits = ["apple", "banana", "cherry"] for i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # 0: apple # 1: banana # 2: cherry # zip() — combine parallel lists names = ["Ali", "Dana", "Marat"] scores = [95, 88, 72] for name, score in zip(names, scores): print(f"{name}: {score}") # map() — apply function to every element nums = ["10", "20", "30"] ints = list(map(int, nums)) # [10, 20, 30] squares = list(map(lambda x: x**2, [1,2,3,4])) # [1, 4, 9, 16] # filter() — keep elements that satisfy condition nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4, 6, 8, 10] # List comprehension with condition (alternative to filter) evens2 = [x for x in nums if x % 2 == 0] # [2, 4, 6, 8, 10] # sorted() with key function words = ["banana", "apple", "Cherry", "date"] print(sorted(words)) # Default: case-sensitive print(sorted(words, key=str.lower)) # Case-insensitive print(sorted(words, key=len)) # By length

Choosing the Right Approach

map()/filter() are functional-style tools. List comprehensions are often more Pythonic and readable for the same tasks. Choose whichever is clearer for the problem at hand.

Worked Examples

1 Caesar Cipher

def caesar_encrypt(text, shift): result = "" for char in text: if char.isalpha(): base = ord('A') if char.isupper() else ord('a') shifted = (ord(char) - base + shift) % 26 + base result += chr(shifted) else: result += char # Keep spaces, punctuation return result message = "Hello World" encrypted = caesar_encrypt(message, 3) print(encrypted) # "Khoor Zruog" # Decrypt by shifting backwards decrypted = caesar_encrypt(encrypted, -3) print(decrypted) # "Hello World"

2 Grade Report with enumerate() and zip()

students = ["Ali", "Dana", "Marat", "Aisha"] math = [85, 92, 78, 96] cs = [90, 88, 82, 95] print("Grade Report:") print(f"{'#':>3} {'Name':<10} {'Math':>6} {'CS':>6} {'Avg':>6}") print("-" * 35) for i, (name, m, c) in enumerate(zip(students, math, cs), 1): avg = (m + c) / 2 print(f"{i:>3} {name:<10} {m:>6} {c:>6} {avg:>6.1f}")

3 Frequency Counter

text = "hello world programming" # Count character frequency freq = {} for char in text: if char != " ": freq[char] = freq.get(char, 0) + 1 # Sort by frequency (most common first) sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True) for char, count in sorted_freq[:5]: print(f"'{char}': {'█' * count} ({count})")

Pitfalls & Common Errors

zip() Stops at Shortest

zip([1,2,3], [4,5]) gives only 2 pairs. If lengths differ, the extra elements are silently ignored.

map() Returns an Iterator

map(int, ["1","2","3"]) returns a map object, not a list. Wrap in list() to get a list.

ord() with Multi-Character Strings

ord("AB") raises TypeError. ord() accepts only a single character.

Pro-Tips for Exams

Quick Reference

  • enumerate(lst, start=1) — start counting from 1 instead of 0
  • sorted(lst, key=len) — sort by string length
  • ord('A')=65, ord('a')=97, ord('0')=48 — memorize these!
  • Caesar shift formula: (ord(c) - base + shift) % 26 + base

Graded Tasks

Remember

What do ord() and chr() do? Give the ASCII values for 'A', 'Z', 'a', 'z'.

Understand

Explain the difference between map() and a list comprehension.

Apply

Use enumerate() and zip() to print a numbered comparison of two lists side by side.

Apply

Write a Caesar cipher that encrypts and decrypts messages with a user-chosen shift value.

Analyze

What is the output of list(filter(lambda x: len(x) > 3, ["hi", "hello", "hey", "world"]))?

Create

Build a character frequency analyzer that reads a text and displays a horizontal bar chart of the top 10 characters.

Self-Check Quiz

1. What does ord('A') return?
Click to reveal answer
2. What does enumerate(['x','y','z']) produce?
Click to reveal answer
3. What does list(zip([1,2], ['a','b'])) give?
Click to reveal answer
4. What does 'hello'.center(11, '*') return?
Click to reveal answer
5. What is the purpose of key in sorted()?
Click to reveal answer