Course contentsShow
← AI Engineering
Lesson 148 of 1,8864. Prompt Engineering FoundationsFree lesson

Basic String Substitution and f-strings

Use Python f-strings and format() to insert variables into prompts for dynamic content generation.

Basic String Substitution and f-strings

What you'll learn: How to use Python f-strings and .format() to dynamically insert variables into prompts, making your AI interactions flexible and reusable.

Why Dynamic Prompts Matter

You've learned about prompt templates and why reusability matters. Now you need the mechanics: how do you actually insert different values into the same prompt structure? This is where Python's string formatting tools become essential.

Plain English First

Imagine you have a form letter: "Dear [NAME], thank you for your purchase of [PRODUCT]." Instead of rewriting the entire letter for each customer, you just fill in the blanks. String substitution does exactly this for prompts—you define the structure once, then swap in different values.

Two Main Approaches

Using f-strings (Modern Python)

F-strings let you embed variables directly inside strings by prefixing with f and using {variable} syntax:

topic = "machine learning"
difficulty = "beginner"

prompt = f"Explain {topic} at a {difficulty} level in 100 words."
# Result: "Explain machine learning at a beginner level in 100 words."

Using .format() Method

The .format() method offers more flexibility for complex templates:

template = "Translate '{text}' from {source_lang} to {target_lang}."
prompt = template.format(text="hello", source_lang="English", target_lang="Spanish")
# Result: "Translate 'hello' from English to Spanish."

When to Use Which

Use f-strings when variables are immediately available—they're cleaner and faster. Use .format() when you're creating reusable template strings stored separately from the data.

Key Takeaway: F-strings and .format() turn static prompts into dynamic templates by letting you inject variables programmatically, enabling you to generate personalized prompts at scale without repetitive code.