Advanced Text Processing
Learn about Advanced Text Processing in COS 102. Comprehensive study materials and practice questions.
Study Document
This document can't be previewed directly.
Open documentStudy Notes
COS 102COS102: Advanced Text Processing
Mastering String Manipulation in Python
This module focuses on advanced text processing techniques in Python, covering string slicing, formatting with f-strings, and essential string methods for efficient text manipulation.
Learning Outcomes
- Master text extraction using String Slicing boundaries.
- Implement negative indexing to safely traverse text backwards.
- Dynamically inject values into strings using modern f-strings.
- Leverage native string methods to clean, parse, and validate text.
- Handle structural data extractions like email and matric numbers.
What is String Slicing?
While indexing allows you to access a single character, Slicing enables you to extract an entire substring or segment from a string.
The Bread Analogy
Instead of inspecting just one crumb, slicing lets you specify where to start and stop "cutting" to pull out a clean "slice" of text.
Slicing Syntax Matrix
Slicing uses square brackets with colons to define the target limits: string[start:stop]
P y t h o n
0 1 2 3 4 5
word = "Python"
print(word[0:2]) # Output: 'Py'
print(word[2:5]) # Output: 'tho'
▲ The Off-By-One Reminder:
Python includes the start index, but completely excludes the stop index!
Slicing Shortcuts
Parameters can be left blank to trigger automatic default values:
- Omit Start (
[:stop]): Starts from index 0."Python"[:4] → 'Pyth' - Omit Stop (
[start:]): Goes all the way to the end."Python"[2:] → 'thon' - Omit Both (
[:]): Clones the entire string.
Negative Slicing Limits
Negative indexing allows you to pull characters from the end of a string without counting from zero.
P y t h o n
-6 -5 -4 -3 -2 -1
filename = "report.txt"
# Extract the extension using negative steps
ext = filename[-4:]
print(ext) # Output: '.txt'
String Formatting (f-Strings)
Old concatenation using + is clunky and error-prone. Modern Python uses f-strings (Formatted String Literals) to easily embed variables inside strings.
name = "Tolani"
score = 85
# Put an 'f' before the quotes, and wrap variables in curly braces {}
msg = f"Hello {name}, your score is {score}."
print(msg) # Output: Hello Tolani, your score is 85.
Inline f-String Math
f-strings can also evaluate active expressions and format numbers on the fly.
price = 2500
discount = 0.10
print(f"Total: #{price * (1 - discount)}")
# Output: Total: #2250.0
val = 22 / 7
print(f"Pi to 2 decimals: {val:.2f}")
# Output: Pi to 2 decimals: 3.14
Essential String Methods
String methods are built-in operations that can be run on text variables using the dot (.) operator.
.upper() / .lower(): Converts character casing completely."Hi".upper() → "HI".strip(): Removes leading/trailing whitespaces." x ".strip() → "x".replace(old, new): Swaps character sub-segments."abc".replace("b", "z") → "azc".split(separator): Breaks text into a list of chunks."a,b".split(",") → ["a", "b"]
Strings are Immutable!
Immutable means a string cannot be altered once it's created in memory.
name = "Python"
name[0] = "J" # CRASH! TypeError!
String methods do not modify the original text; instead, they return a brand new string value that you have to save into a variable.
Lab: Email Domain Extractor (Code Challenge)
Write a program that takes a user's input email address, extracts the domain name using string methods, and prints a clean greeting.
email = " student@unilag.edu.ng "
# 1. Clean the outer whitespace
# 2. Extract everything after the "@" symbol
# 3. Print a message using an f-string
Questions?
Text processing transforms raw data into structured information inputs.
Next Chapter: Error and Exception Handling (Try / Except)