Learn AI
~40 minIn progress

Phase 1 · Programming Fundamentals

Strings & Text Processing

Slice, clean, and format text—skills you’ll reuse in every NLP and data pipeline later.

~40 min4 sections2 exercisesQuiz · pass 4/5
On this page
  1. 01Indexing and slicing
  2. 02Useful string methods
  3. 03Formatting with f-strings
  4. 04Looping and building text
  5. 05Mini challenge: username normalizer
  6. 06Try It
  7. 07Quiz

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().

Index and slice
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.

Cleaning and checking
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"))         # 2
split and join
line = "ada,grace,alan"
names = line.split(",")
print(names)  # ['ada', 'grace', 'alan']

csv = " | ".join(names)
print(csv)    # ada | grace | alan

split() 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.

Number and width formatting
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.0314

Looping 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.

Words and filters
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)  # True

List 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.

challenge starter
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.

1.What does s[1:4] return for s = "abcdef"?
2.Why does s[0] = "X" fail on a string?
3.What does "a,b,c".split(",") return?
4.Which expression joins words with spaces?
5.What does f"{0.956:.1%}" roughly print?