g↗genai/ learner
Python for AI / Lesson 03

Strings

Building AI applications means transforming unstructured user queries, cleaning messy webhooks, interpolating variables into prompt templates, and parsing model outputs. Python strings provide the computational foundation to clean, structure, and format text reliably.

Concept + interactive labBeginner friendly

Quotes: Choosing boundaries for prompts and text.

In Python, text is represented as a string (type str). You create strings by wrapping characters in quote delimiters. Python offers single quotes ('...'), double quotes ("..."), and triple quotes ("""...""").

While single and double quotes behave identically, choosing double quotes prevents common syntax errors when your text contains apostrophes:

# The apostrophe terminates a single-quoted string prematurely:

bad_query = 'Don't hallucinate' # SyntaxError: unterminated string

# Double quotes allow apostrophes to sit harmlessly inside:

safe_query = "Don't hallucinate" # Clean and valid

When you write long system instructions for an LLM that span multiple lines, use triple quotes. Triple quotes preserve all line breaks and formatting verbatim:

system_prompt = """You are an AI support assistant.
Follow these rules:
1. Be concise and polite.
2. Cite reference order numbers."""

Educational diagram illustrating Python string quotes, string immutability in memory, and f-string prompt variable interpolation
Figure 1: The three mental models of Python strings in AI: quote delimiters for apostrophes and multiline prompts, string immutability across method calls, and f-string variable interpolation.

Cleaning and immutability: Stripping whitespace and lowercasing.

Real user inputs arriving into an AI pipeline rarely arrive clean. Webhooks and chat boxes frequently introduce trailing spaces, irregular capitalization, and stray characters:

raw_query = " RefunD for Order #881 "

Python provides string methods to clean this data before passing it to embeddings or intent classifiers:

  • .strip(): Trims whitespace (spaces, tabs, newlines) from both the start and end of the string. It does not remove spaces between words.
  • .lower(): Converts all uppercase letters to lowercase, preventing case discrepancies between user searches and database keys.

You can chain these methods left-to-right to clean the query in a single concise line:

# .strip() runs first on raw_query, then .lower() runs on the stripped result:

clean_query = raw_query.strip().lower()

# Result stored in clean_query: "refund for order #881"
Fundamental Concept: Strings are Immutable. In Python, strings cannot be changed after creation. String methods never modify the original object in memory; they return a brand new string. If you write raw_query.strip() without storing the return value (e.g. clean = raw_query.strip()), the cleaned text is discarded and raw_query remains completely unaltered.

String Pipeline: The Immutability Chain

Every method returns a new object
Stage 1

Raw Webhook Input

" RefunD for Order #881 "
Preserves spaces & mixed case
Stage 2

.strip() Whitespace Trim

"RefunD for Order #881"
Trims outer spaces; interior remains
Stage 3

.lower() Normalization

"refund for order #881"
Consistent lowercase casing
Stage 4

f"..." Prompt Injection

"Intent: refund for order #881"
Interpolates clean value into template
Selected Code: raw = " RefunD for Order #881 "
Notice how the variable names are reassigned. Python never modifies the original string in place!

Transforming: Replacing tokens and splitting words.

Beyond trimming whitespace and adjusting casing, pipelines often need to sanitize punctuation or isolate individual words:

# Replace target characters: replace(old, new)

clean_query = clean_query.replace("#", "no. ")

# clean_query is now: "refund for order no. 881"

Notice again that we reassigned clean_query! Because strings are immutable, calling .replace() without saving its return value leaves the string unchanged.

When you want to count words or inspect tokens, use .split(). By default, .split() slices the string wherever whitespace occurs and returns the words grouped in brackets [...]:

words = clean_query.split()

# words evaluates to: ['refund', 'for', 'order', 'no.', '881']

Note: Python groups separated words into a list ([...]). We will explore list indexing, slicing, and list methods in depth in Lesson 04 (Lists).

F-strings: Interpolating dynamic prompts safely.

Modern LLM applications rarely send static text. Instead, you construct dynamic prompts combining system instructions, user names, and cleaned queries.

In modern Python, you do this using f-strings (formatted string literals). Place the letter f directly before the opening quote, and place any Python variable or expression inside curly braces {...}:

user_id = "Alex"

prompt = f"User: {user_id}\nQuery: {clean_query}"

# Evaluates to:
# "User: Alex\nQuery: refund for order no. 881"
The Missing 'f' Trap: If you omit the leading f and write "User: {user_id}", Python treats the curly braces as literal characters. The AI model receives the text {user_id} rather than Alex. Always double-check that your prompt template begins with f.

You can check the total character length of any string using the built-in len() function:

prompt_chars = len(prompt) # Returns integer count, e.g., 42

While len(prompt) provides a quick character count heuristic (roughly 4 characters per token in typical English text), production AI applications use dedicated model tokenizers to measure true token usage. Character counting provides a fast initial sanity check, while the model's tokenizer and total request budget (including system instructions and reserved completion tokens) enforce strict context limits.

Inspect string transformations in the AI prompt sandbox.

Experiment with how raw webhook text, whitespace trimming, casing, character replacements, and f-string interpolation interact in a live pipeline:

AI Prompt & String Sandbox

Test how Python quotes, whitespace stripping, case normalization, and f-string prompt templating prepare unstructured user input for AI models.

Presets:
Immutability Inspector: Separate Memory Objects✓ raw_query UNCHANGED in memory
Name tag: raw_query
" RefunD for Order #881 "
Original object in memory: never modified.
Name tag: clean_query
"refund for order no. 881"
Brand new string created by method chaining.
Rendered Prompt to LLM API (f"...")len(prompt) = 42 chars
User: Alex
Query: refund for order no. 881

Try it in this order:

  1. Observe how unchecking .strip() leaves dirty leading and trailing spaces in the prompt.
  2. Inspect the Immutability Inspector to verify that raw_query remains completely unchanged regardless of what methods run.
  3. Toggle off the Include 'f' prefix checkbox to observe the infamous missing 'f' bug where braces leak into the API call.
  4. Turn on Preview .split() to see how Python slices the string into discrete word items.
✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

An AI engineer receives raw customer input and writes the following pipeline code: raw_query = ' RefunD for Order #881 ' raw_query.strip().lower() prompt = f'Process: {raw_query}' What exact text is stored in prompt?
THE TAKEAWAY

Take this with you.

Python strings (str) are the backbone of prompt engineering and AI data preparation. Use double quotes ("...") to avoid apostrophe syntax bugs, and triple quotes ("""...""") for multiline prompts. Remember that strings are immutable: methods like .strip() and .lower() return brand new strings and leave the original untouched. When building prompts, always prefix templates with f (f"...{var}...") so expressions evaluate to real values, and monitor prompt size with len().

Next up: Lists in Chapter P1 →