Index Ai Academy
Phase 0 · ToolsPython core

Strings and f-strings

About 25 minLooking ahead: some prerequisites aren't done yet

Why this matters

A prompt is a string. A model's reply is a string. Most of the data you'll feed an AI system starts as messy text: subject lines with stray spaces, tags in mixed capitals, product names pasted from three different tools. Cleaning text, and building it from pieces, are skills you'll use in nearly every AI project. The first big use is building prompts from data.

  • Pull out characters and slices of text with indexes
  • Clean and reshape text with string methods
  • Build text from variables with f-strings, including formatted numbers
  • Write multi-line text and special characters

Text in quotes

A string is a piece of text. Picture a row of letter tiles: each tile is one character, and the row is the string. Single and double quotes work the same way, so pick the one that doesn't clash with the text inside:

headline = "It's our biggest sale"
quote = 'She said "worth every penny"'
print(headline)
print(quote)

Three handy tools:

  • + joins strings end to end,
  • * repeats them,
  • len() counts the characters, spaces and punctuation included.
first = "Spring"
second = "Sale"
print(first + " " + second)
print("-" * 20)
print(len("Spring Sale"))

Indexing and slicing

Every character in a string has a position, called its index. Counting starts at 0, not

  1. Negative indexes count from the end: -1 is the last character.
  • code[0] is the first character.
  • code[-1] is the last.
  • code[2:6] is a slice: from index 2 up to, but not including, index 6.
  • Leave out a side to go to the edge: code[:8] is the first 8 characters, code[9:] is everything from index 9 on.

Drag the handles below and watch the expression and its result change.