Chapter 8

Strings and Text

8.0 Overview · 8.1 Strings · 8.2 Regex · 8.3 Text Analysis

← → or Space to navigate · F for fullscreen

8.1 Strings

Methods, comparison, looping, sorting

String Methods

s = "  Hello, World!  "

print(s.strip())          # 'Hello, World!'
print(s.lower())          # '  hello, world!  '
print(s.upper())
print(s.replace("World", "Python"))
print(s.split(", "))      # ['  Hello', 'World!  ']
print(",".join(["a","b","c"])) # 'a,b,c'

Testing methods

"hello".startswith("he")   # True
"hello123".isalnum()        # True
"   ".isspace()             # True
"Hello".istitle()           # True

# Check and membership
"ell" in "hello"            # True
"hello".find("ll")          # 2  (-1 if not found)
"hello".count("l")          # 2

String Comparison & Sorting

Strings compare lexicographically using Unicode code points.

print("apple" < "banana")   # True
print("B" < "a")            # True  (uppercase < lowercase)
print(ord("A"), ord("a"))   # 65 97

Sorting strings

words = ["banana", "apple", "Cherry", "date"]

# Default: case-sensitive (uppercase first)
print(sorted(words))
# ['Cherry', 'apple', 'banana', 'date']

# Case-insensitive
print(sorted(words, key=str.casefold))
# ['apple', 'banana', 'Cherry', 'date']

# By length
print(sorted(words, key=len))

Splitting, Joining, and Validation

text = "  too   many   spaces  "
print(" ".join(text.split()))  # too many spaces
print(",".join("a,,b".split(",")))  # a,,b

Whitespace splitting discards spacing. An explicit delimiter preserves empty fields.

print("²".isdigit())  # True
# int("²") raises ValueError: classification is not conversion.

Use try / except ValueError when accepting an integer.

8.2 Regular Expressions

Pattern matching with the re module

re Module Basics

Function Returns
re.search(pat, s) First match object or None
re.findall(pat, s) List of all matches
re.sub(pat, rep, s) String with replacements
re.compile(pat) Compiled pattern object
import re

text = "Call 555-1234 or 555-5678 for info."

# Find all phone numbers
phones = re.findall(r"\d{3}-\d{4}", text)
print(phones)   # ['555-1234', '555-5678']

# Replace
clean = re.sub(r"\d{3}-\d{4}", "XXX-XXXX", text)

Key Regex Patterns

Learn character classes, then quantifiers, anchors, groups, and flags.

Pattern Matches
. Any character except newline
\d Unicode decimal digit · [0-9] for ASCII digits
\w Word char (letter/digit/_) · \W non-word
\s Whitespace · \S non-whitespace
^ / $ Start / end of string
* + ? 0+, 1+, 0 or 1 occurrences
{n} {m,n} Exactly n, or m to n occurrences
[abc] Any of a, b, c
(...) Capturing group

Capturing Changes the Result

import re
text = "2024-03"
print(re.findall(r"\d{4}-\d{2}", text))      # ['2024-03']
print(re.findall(r"(\d{4})-\d{2}", text))    # ['2024']
print(re.findall(r"(\d{4})-(\d{2})", text))  # [('2024', '03')]
Capturing groups findall() returns
None Complete match strings
One Captured strings
Two or more Tuples of captured strings

Search, Match, or Validate?

Pattern: EMP-[0-9]{4}

Input search() match() fullmatch()
EMP-0001 True True True
xEMP-0001 True False False
EMP-0001junk True True False

search() finds a match anywhere. match() requires a matching prefix.
fullmatch() requires the whole input, so it checks the complete ID format.

Check for None before accessing a match's .group() or .span().

8.3 Text Analysis

Cleaning, word frequencies, Counter, Markov generation

Word Frequencies & Counter

Manual approach

text = "Hello hello! pocket-handkerchief !!!"
words = []
for raw_word in text.split():
    word = raw_word.strip(".,!?").lower()
    if word:
        words.append(word)

word_counter = {}
for word in words:
    word_counter[word] = word_counter.get(word, 0) + 1

# Sort by frequency
items = sorted(word_counter.items(),
               key=lambda t: t[1], reverse=True)

With Counter

from collections import Counter

# Reuse the SAME cleaned tokens.
counts = Counter(words)

# Top 5 words
for word, freq in counts.most_common(5):
    print(freq, word, sep="\t")

Counter replaces the manual loop and adds .most_common() directly.

Cleaning Defines the Vocabulary

Raw text Cleaned tokens Consequence
Hello hello! hello, hello One unique word; two tokens
coolness—frightened coolness, frightened Dash creates a boundary
pocket-handkerchief pocket-handkerchief Internal hyphen remains
!!! None Discard empty tokens

Replacing the internal hyphen with a space changes vocabulary and token counts.
Use the same policy for unique words, frequencies, bigrams, and generation.

The notebook reads UTF-8 text from the project data directory once,
then develops each stage. Explicit resets restore corpus state after exercises.

Trace the Bigram Window

Incoming word After append Pair counted After pop
the ['the'] None ['the']
cat ['the', 'cat'] ('the', 'cat') ['cat']
sat ['cat', 'sat'] ('cat', 'sat') ['sat']

Reset the window and counts before rebuilding the model.
This model keeps adjacent tokens across line and sentence boundaries.

Successors Encode Conditional Probability

{'cat': ['sat', 'sat', 'slept']}

Next word, given cat Probability
sat 2/3
slept 1/3

Choose a list position uniformly. Repeated words retain observed frequencies.
Deduplicating the list would change the model.

A first-order Markov model uses the current word to choose the next word.

Generation Must Have a Stopping Rule

import random
model = {'cat': ['sat'], 'sat': ['on'], 'on': ['mat']}
word = 'cat'
result = [word]
for _ in range(10):
    successors = model.get(word, [])
    if not successors:
        break
    word = random.choice(successors)
    result.append(word)
print(' '.join(result))  # cat sat on mat

Stop at the length limit or a word without successors.

Chapter 8: Quick Reference

Concept Key syntax / notes
Strip / clean .strip(), .lower(), .replace()
Split / join .split(sep), sep.join(seq)
Membership "sub" in s, .find(), .count()
Regex search re.search(pattern, string)
Find all re.findall(pattern, string)
Substitute re.sub(pattern, repl, string)
Compile re.compile(pattern) for reuse
Word freq Counter(words).most_common(n)
Markov {word: [successor, ...]}; repeats encode frequency

End of Chapter 8

Next: Chapter 9: Object-Oriented Programming

classes · instances · inheritance · polymorphism