Phase 1 · Programming Fundamentals
Strings & Text Processing
Slice, clean, and format text—skills you’ll reuse in every NLP and data pipeline later.
On this page
Indexing and slicing
A string is an ordered sequence of characters. Index from 0; negative indexes count from the end.
Slicing uses start:stop:step. The stop index is exclusive—same rule as range().
text = "LearnAI"
print(text[0]) # L
print(text[-1]) # I
print(text[0:5]) # Learn
print(text[5:]) # AI
print(text[::-1]) # IAnraeL (reversed)Strings are immutable—you cannot do text[0] = "X". Build a new string instead.
Useful string methods
Methods return a new string (or a list). Chain them when each step cleans the text a little more.
Common ones: lower, upper, strip, replace, startswith, endswith, split, join, find, count.
raw = " Machine Learning "
clean = raw.strip().lower()
print(clean) # machine learning
print(clean.startswith("mach")) # True
print(clean.replace(" ", "_")) # machine_learning
print(clean.count("a")) # 2line = "ada,grace,alan"
names = line.split(",")
print(names) # ['ada', 'grace', 'alan']
csv = " | ".join(names)
print(csv) # ada | grace | alansplit() with no argument splits on any whitespace and drops empty pieces—great for messy input.
Formatting with f-strings
f-strings embed expressions in {}. You can format numbers (decimals, percent) and pad text.
Prefer f-strings over + concatenation for readability.
score = 0.956
name = "Ada"
print(f"{name} scored {score:.1%}") # Ada scored 95.6%
print(f"{name:>10}") # right-aligned
print(f"loss={0.0314:.4f}") # loss=0.0314Looping and building text
You can loop over characters or over words after split(). Use a list + join to build long strings efficiently.
Membership with in checks for a substring.
sentence = "AI will change how we build software"
words = sentence.lower().split()
long_words = [w for w in words if len(w) > 3]
print(long_words)
print("build" in sentence) # TrueList comprehensions pair well with split() for quick text filters—you’ll see this pattern in NLP prep.
Practice
Mini challenge: username normalizer
Ask for a display name. Strip spaces, lowercase it, replace spaces with underscores, and print a slug like @ada_lovelace. Reject empty input with a clear message.
raw = input("Display name: ")
# TODO: normalize to @slug
# tip: strip, lower, replace spaces with _
Interactive
Try It in the browser
Powered by Pyodide
Given messy = " Deep Learning 101 ", produce "deep-learning-101" by stripping, lowercasing, splitting on whitespace, and joining with hyphens.
Output
—
Errors
—
Check understanding
Lesson quiz
Score 4/5 or higher to mark this day complete.