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.
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:
bad_query = 'Don't hallucinate' # SyntaxError: unterminated string
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."""

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:
clean_query = raw_query.strip().lower()
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 objectRaw Webhook Input
.strip() Whitespace Trim
.lower() Normalization
f"..." Prompt Injection
raw = " RefunD for Order #881 "Transforming: Replacing tokens and splitting words.
Beyond trimming whitespace and adjusting casing, pipelines often need to sanitize punctuation or isolate individual words:
clean_query = clean_query.replace("#", "no. ")
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()
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}"
# "User: Alex\nQuery: refund for order no. 881"
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.
f"...")len(prompt) = 42 charsUser: Alex Query: refund for order no. 881
Try it in this order:
- Observe how unchecking
.strip()leaves dirty leading and trailing spaces in the prompt. - Inspect the Immutability Inspector to verify that
raw_queryremains completely unchanged regardless of what methods run. - Toggle off the Include 'f' prefix checkbox to observe the infamous missing 'f' bug where braces leak into the API call.
- Turn on Preview .split() to see how Python slices the string into discrete word items.
Check your understanding.
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().