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.
- 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
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])- 1.Line 1: Allocates 14-character string 'SEC_TOKEN_8942'.
- 2.Line 4: len() evaluates to integer 14.
- 3.Line 5: token[0] retrieves 'S'.
- 4.Line 7: token[-1] retrieves '2' (the last character).
- 5.Line 8: token[-2] retrieves '4'.
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
• 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]
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])- 1.Line 4: email[:11] extracts characters 0 through 10 -> 'student.coe'.
- 2.Line 5: email[12:] extracts index 12 to end -> 'datascience.org'.
- 3.Line 11: alpha[::2] picks index 0, 2, 4, 6, 8 -> 'ACEGI'.
- 4.Line 12: alpha[::-1] traverses backwards with step -1 -> 'JIHGFEDCBA'.
Username : student.coe Domain : datascience.org Every 2nd char : ACEGI Reversed string: JIHGFEDCBA
• 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
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("!"))- 1.Line 4: .strip() trims the 3 leading spaces and trailing whitespace/newline.
- 2.Line 5: .lower() converts all uppercase characters to lowercase.
- 3.Line 12: .replace() finds the exact phrase and substitutes '[CONFIDENTIAL]'.
- 4.Lines 16-17: .startswith() and .endswith() evaluate boolean predicates.
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
• 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
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)- 1.Line 3: Splits log_entry into a 4-element list of strings.
- 2.Line 10: message.split() neatly handles erratic multiple spaces, extracting exactly 4 words.
- 3.Line 14: Glues words together using ' -> ' as separator.
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
• 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()
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- 1.Line 5: 'urgent' in cleaned_subj evaluates to False.
- 2.Line 6: 'prize' in cleaned_subj evaluates to True.
- 3.Line 11: .find('prize') locates 'prize' starting at index 39.
- 4.Line 14: .find('wire transfer') returns -1 indicating absence.
'urgent' in subject : False 'prize' in subject : True 'verify' in subject : True Position of 'prize' : 39 Position of missing : -1
• 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
basicModify 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.
Enterprise Security Log Sanitizer & Secret Redactor
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.
- 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.
- 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.
# 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
Chapter summary
Key concepts and syntax cards for review
- 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.
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'])?