Ch 03Strings and Text Processing
Chapter 03 of 08·20 min

Strings and Text Processing

Text is the most ubiquitous data format in computer science—from web traffic and email payloads to genomic sequences and large language model corpora. In this chapter, you will master the mechanics of Python strings: zero-based indexing, slicing with step strides, immutability, essential string cleaning methods, tokenization with split and join, and fast substring scanning. These techniques directly empower our Inbox Guardian security engine.

Learning objectives
  • 01Navigate string characters using positive and negative zero-based indexing and understand string immutability
  • 02Extract substrings using slice notation [start:stop:step] and reverse sequences efficiently with [::-1]
  • 03Clean messy inputs using .strip(), .lower(), .upper(), and replace target patterns with .replace()
  • 04Deconstruct text into lists using .split() and reassemble sequences with .join()
  • 05Perform fast substring search using .find(), .count(), .startswith(), and the 'in' membership operator
  • 06Analyze and avoid critical edge cases: IndexError vs slice boundary safety, string immutability TypeError, and empty substring truthiness

3.1 Zero-Based Indexing & String Immutability

In Python, a string is an **ordered sequence of Unicode characters**. Every character occupies an exact integer index. ### Indexing Conventions: - **Forward Indexing (Positive)**: Starts at `0` for the first character, incrementing up to `len(s) - 1`. - **Backward Indexing (Negative)**: Starts at `-1` for the last character, `-2` for the second-to-last, down to `-len(s)` for the first. ### String Immutability: Strings in Python are strictly **immutable**. Once created in memory, individual characters **cannot be modified, deleted, or replaced in place**. Attempting `text[0] = 'H'` raises a `TypeError`. Any operation that appears to modify a string actually allocates and returns a completely new string object.
Statement 1: Accessing Characters by Index

Forward indexing, negative indexing, and len() verification.

token = "SEC_TOKEN_8942"

print("Full Token     :", token)
print("Length of token:", len(token))
print("First character (index 0) :", token[0])
print("Fourth character (index 3):", token[3])
print("Last character (index -1) :", token[-1])
print("Penultimate char (index -2):", token[-2])
Execution walkthrough
  1. 1.Line 1: Allocates 14-character string 'SEC_TOKEN_8942'.
  2. 2.Line 4: len() evaluates to integer 14.
  3. 3.Line 5: token[0] retrieves 'S'.
  4. 4.Line 7: token[-1] retrieves '2' (the last character).
  5. 5.Line 8: token[-2] retrieves '4'.
Expected output
Full Token     : SEC_TOKEN_8942
Length of token: 14
First character (index 0) : S
Fourth character (index 3): _
Last character (index -1) : 2
Penultimate char (index -2): 4
Edge cases

• IndexError: Accessing token[14] or token[-15] crashes with IndexError: string index out of range. Valid positive indices range from 0 to len - 1. • TypeError on Mutation: Writing token[0] = 'X' raises TypeError: 'str' object does not support item assignment. Strings are completely immutable.

Why it happens: Python resolves negative index -i as len(s) - i under the hood.

3.2 Slicing Strings: [start:stop:step]

Slicing allows you to extract an entire sub-sequence of characters using the syntax: `sequence[start:stop:step]` - `start`: The index of the first character to include (inclusive, default `0`). - `stop`: The index where slicing terminates (**exclusive**, does not include character at stop, default `len`). - `step`: The stride increment between characters (default `1`). ### Idiomatic Slicing Patterns: - `text[:5]`: First 5 characters (indices 0, 1, 2, 3, 4). - `text[3:]`: From index 3 through the very end. - `text[::2]`: Every second character. - `text[::-1]`: **Reverses the entire string** using negative step.
Statement 2: Substring Extraction via Slicing

Extracting prefixes, domains, stepped characters, and reversing strings.

email = "student.coe@datascience.org"

# Prefix and domain extraction
username = email[:11]          # indices 0 through 10
domain   = email[12:]          # index 12 to end
print("Username :", username)
print("Domain   :", domain)

# Stepped slicing and string reversal
alpha = "ABCDEFGHIJ"
print("Every 2nd char :", alpha[::2])
print("Reversed string:", alpha[::-1])
Execution walkthrough
  1. 1.Line 4: email[:11] extracts characters 0 through 10 -> 'student.coe'.
  2. 2.Line 5: email[12:] extracts index 12 to end -> 'datascience.org'.
  3. 3.Line 11: alpha[::2] picks index 0, 2, 4, 6, 8 -> 'ACEGI'.
  4. 4.Line 12: alpha[::-1] traverses backwards with step -1 -> 'JIHGFEDCBA'.
Expected output
Username : student.coe
Domain   : datascience.org
Every 2nd char : ACEGI
Reversed string: JIHGFEDCBA
Edge cases

• Slicing NEVER raises an IndexError: Even if start or stop exceed string bounds (e.g. 'hello'[10:50]), Python returns an empty string '' or the valid portion without crashing! Indexing crashes; slicing is safe. • Inverted bounds: 'hello'[4:2] with positive step returns '' because moving forward from 4 cannot reach 2.

Why it happens: Python slices handle boundaries gracefully without memory faults.

3.3 Essential String Methods: Cleaning & Normalization

Real-world data is notoriously messy: user inputs contain stray spaces, erratic capitalization, and unexpected punctuation. Python provides built-in methods to clean and standardize text. ### Core Methods for Text Normalization: - `.lower()` / `.upper()`: Converts all characters to lowercase or uppercase. - `.strip()`: Strips leading and trailing whitespace (`\n`, `\t`, spaces). - `.replace(old, new, count)`: Replaces occurrences of a substring with another string. - `.count(sub)`: Counts non-overlapping occurrences of a substring. - `.startswith(prefix)` / `.endswith(suffix)`: Returns boolean testing start or end.
Statement 3: Normalizing & Sanitizing Strings

Cleaning whitespace, case-folding, and replacing sensitive tokens.

raw_input = "   URGENT: Verify Your Bank Credentials IMMEDIATELY!   \n"

# Normalization pipeline
cleaned = raw_input.strip()            # Removes outer whitespace & \n
normalized = cleaned.lower()           # Case folding for search

print("Raw length       :", len(raw_input))
print("Cleaned length   :", len(cleaned))
print("Normalized text  :", normalized)

# Substring replacement
sanitized = normalized.replace("bank credentials", "[CONFIDENTIAL]")
print("Sanitized text   :", sanitized)

# Prefix / Suffix inspection
print("Starts with urgent :", normalized.startswith("urgent"))
print("Ends with '!'      :", normalized.endswith("!"))
Execution walkthrough
  1. 1.Line 4: .strip() trims the 3 leading spaces and trailing whitespace/newline.
  2. 2.Line 5: .lower() converts all uppercase characters to lowercase.
  3. 3.Line 12: .replace() finds the exact phrase and substitutes '[CONFIDENTIAL]'.
  4. 4.Lines 16-17: .startswith() and .endswith() evaluate boolean predicates.
Expected output
Raw length       : 56
Cleaned length   : 49
Normalized text  : urgent: verify your bank credentials immediately!
Sanitized text   : urgent: verify your [CONFIDENTIAL] immediately!
Starts with urgent : True
Ends with '!'      : True
Edge cases

• Forgetting Reassignment: Writing `raw_input.strip()` on its own does NOT modify `raw_input`! You must assign the result: `raw_input = raw_input.strip()`. • .strip('xyz') specificity: Passing characters to .strip('xyz') strips any combination of those characters from ends, NOT the whole phrase.

Why it happens: Each string method returns a new string object, leaving the original raw_input variable unaltered.

3.4 Splitting, Joining & Tokenization

Converting continuous text into structured lists (and vice versa) is the backbone of text analysis. ### The Two Dual Methods: - **`str.split(delimiter)`**: Splits a string into a **list of strings** based on a delimiter. If no delimiter is passed, it automatically splits by any run of whitespace (spaces, tabs, newlines) and discards empty tokens. - **`delimiter.join(iterable)`**: Joins an iterable of strings into a single cohesive string, placing the delimiter between every element.
Statement 4: Tokenizing with .split() and Reassembling with .join()

Breaking comma-separated values into tokens and joining with custom glues.

# Splitting a CSV log line
log_entry = "2026-11-17,AUTH_LOGIN,192.168.1.104,SUCCESS"
tokens = log_entry.split(",")
print("Token list:", tokens)
print("Timestamp :", tokens[0])
print("IP Address:", tokens[2])

# Whitespace tokenization (words)
message = "Analyze   email   urgency    heuristics"
words = message.split()  # Splits on arbitrary consecutive whitespace
print("Words     :", words)

# Joining tokens back into a formatted line
formatted_csv = " -> ".join(words)
print("Joined    :", formatted_csv)
Execution walkthrough
  1. 1.Line 3: Splits log_entry into a 4-element list of strings.
  2. 2.Line 10: message.split() neatly handles erratic multiple spaces, extracting exactly 4 words.
  3. 3.Line 14: Glues words together using ' -> ' as separator.
Expected output
Token list: ['2026-11-17', 'AUTH_LOGIN', '192.168.1.104', 'SUCCESS']
Timestamp : 2026-11-17
IP Address: 192.168.1.104
Words     : ['Analyze', 'email', 'urgency', 'heuristics']
Joined    : Analyze -> email -> urgency -> heuristics
Edge cases

• Calling .join() on non-strings: ', '.join([1, 2, 3]) crashes with TypeError: sequence item 0: expected str instance, int found. All items in the list must be strings! (e.g. ', '.join([str(x) for x in nums])).

Why it happens: split() returns a Python list (studied deeply in Chapter 6). join() is called on the separator string.

3.5 Substring Membership with 'in' and .find()

Checking whether a target keyword exists inside a text is the central building block of rule-based classification. Python provides two primary approaches: 1. **`'keyword' in text`**: Returns a boolean `True` or `False`. Highly idiomatic, readable, and fast. 2. **`text.find(keyword)`**: Returns the **starting integer index** where the keyword first appears, or **`-1`** if it does not exist. *(Note: Avoid `.index()` for search because `.index()` raises a `ValueError` if the substring is missing, whereas `.find()` returns `-1` safely.)*
Statement 5: Scanning for Keywords with 'in' and .find()

Evaluating keyword presence and locating exact substring coordinates.

email_subject = "Action Required: Verify Account Access Prize"
cleaned_subj = email_subject.lower()

# Checking presence with 'in'
print("'urgent' in subject :", "urgent" in cleaned_subj)
print("'prize' in subject  :", "prize" in cleaned_subj)
print("'verify' in subject :", "verify" in cleaned_subj)

# Locating index with .find()
prize_pos = cleaned_subj.find("prize")
print("Position of 'prize' :", prize_pos)

missing_pos = cleaned_subj.find("wire transfer")
print("Position of missing :", missing_pos)  # Returns -1
Execution walkthrough
  1. 1.Line 5: 'urgent' in cleaned_subj evaluates to False.
  2. 2.Line 6: 'prize' in cleaned_subj evaluates to True.
  3. 3.Line 11: .find('prize') locates 'prize' starting at index 39.
  4. 4.Line 14: .find('wire transfer') returns -1 indicating absence.
Expected output
'urgent' in subject : False
'prize' in subject  : True
'verify' in subject : True
Position of 'prize' : 39
Position of missing : -1
Edge cases

• The Empty String Trapped: `'' in any_string` is ALWAYS `True`! Python defines the empty string as existing at every position in any sequence. • Case sensitivity: `'FREE' in 'free prize'` is `False`. Always normalize to `.lower()` before performing membership checks.

Why it happens: Python scans the string efficiently to verify whether the target substring exists within the text sequence.

Practice exercise

Work through the exercise before starting the chapter assignment

Exercise 3: Normalizing & Scanning Email Headers

basic

Modify the starter code to clean the subject string by stripping outer whitespace, converting to lowercase, and printing whether the keyword 'free' appears in the cleaned subject.

Chapter 03 assignmentMilestone

Enterprise Security Log Sanitizer & Secret Redactor

Scenario

A security operations center (SOC) at the Center of Excellence intercepts raw network log strings that inadvertently expose user email addresses, API authentication tokens, and trailing whitespace. You must implement a log sanitizer that parses, redacts, and formats log entries before permanent database storage.

Implementation requirements
  • Given a raw log string: ' 2026-11-17 | USER: alex.chen@externalcorp.com | TOKEN: secret_98421_x9 | STATUS: OK \n'
  • Strip leading and trailing whitespace and newlines using .strip().
  • Split the log entry by ' | ' into exactly 4 segments: timestamp, user_segment, token_segment, and status_segment.
  • Extract the email address from user_segment (everything after 'USER: ').
  • Find the '@' index in the email address using .find('@').
  • Redact the email domain using string slicing: keep the username part, and replace the domain with '@[REDACTED]'.
  • Redact the token in token_segment: keep 'TOKEN: ' and replace the secret hash with '***PROTECTED***'.
  • Re-assemble the 4 sanitized segments using ' | '.join(...) and print the final sanitized log.
Edge cases to handle
  • 1.Emails with varying username lengths: Use dynamic .find('@') and slicing [:at_index] rather than hardcoded lengths.
  • 2.Spacing around delimiters: Ensure ' | ' (with spaces) is used consistently to prevent messy concatenation.
  • 3.Handle case variations cleanly.
Starter template
# Chapter 3 Assignment: Security Log Sanitizer & Secret Redactor
# Center of Excellence: Data Science & AI

raw_log = "  2026-11-17 | USER: alex.chen@externalcorp.com | TOKEN: secret_98421_x9 | STATUS: OK  \n"

# 1. Strip raw log whitespace
cleaned_log = raw_log.strip()

# 2. Split log by " | " into segments
# TODO: segments = cleaned_log.split(" | ")

# 3. Extract email and redact domain
# TODO: Locate '@' and slice username
# TODO: Rebuild sanitized_user = "USER: " + username + "@[REDACTED]"

# 4. Redact token segment to "TOKEN: ***PROTECTED***"

# 5. Join segments back with " | " and print final output
Progressive hints

Chapter summary

Key concepts and syntax cards for review

Key concepts
  • 01Strings are immutable sequences: individual characters cannot be modified in place.
  • 02Positive indexing starts at 0; negative indexing counts backwards from -1.
  • 03Slicing [start:stop:step] extracts substrings; stop is exclusive. Slicing never raises an IndexError.
  • 04String methods like .lower(), .upper(), .strip(), and .replace() return new strings without mutating the original.
  • 05split(sep) divides text into a list; sep.join(list) glues a list of strings into one string.
Syntax reference
char = text[0], last = text[-1]Accessing single character by zero-based index.
sub = text[start:stop:step]Slicing substring from start (inclusive) to stop (exclusive).
cleaned = text.strip().lower()Chaining methods to remove whitespace and case-fold.
tokens = text.split(','), combined = ','.join(tokens)Tokenizing text and reassembling lists of strings.

Knowledge check

Verify your grasp of the chapter concepts

What will be returned by: 'Data Science'[-3:]?

What will: ' URGENT '.strip().lower() evaluate to?

What happens when you run: '-'.join(['Alpha', 'Beta', 'Gamma'])?