Sub topic 2
From strings to templates with variables
This chapter assumes you have sent prompts to a large language model, can read basic Python, and know what a text file and a Git repository are. It covers the step from a hard-coded prompt string to a template with named variables. Later chapters cover validation, storage, and versioning in detail.
Why hard-coded strings break down
The first version of a prompt usually lives inside a function as an f-string or as concatenated pieces. This works until the prompt is used in more than one place or edited by more than one person.
Common problems:
- The same instructions get copied into several functions, and the copies drift apart.
- Fixed instructions and variable input are mixed together, so a small wording change means editing logic code.
- Quotes, braces, and newlines inside the prompt make the Python source hard to read.
- You cannot tell which parts of the prompt are meant to change and which are not.
A prompt template fixes this by separating the two. The fixed instructions stay in one block of text. The parts that change are marked as named variables, and values are filled in when the prompt is sent.
A first template
Python's standard library includes string.Template. It marks variables with a $ prefix and needs no extra packages.
from string import Template
template = Template("Summarize the following text in $style style:\n\n$text")
prompt = template.substitute(style="concise", text="Prompt templates separate fixed instructions from variable input.")
print(prompt)The template text has two variables, $style and $text. The call to substitute replaces each one with the value you pass by name. The result is an ordinary string that you send to the model.
Why names matter
Variables are identified by name, not by position. Compare these two calls:
- With positional formatting,
"{} {}".format(a, b)depends on argument order, and swapping two arguments fails silently. - With named variables,
substitute(style=..., text=...)stays correct whatever order you write the arguments in.
Names also act as documentation. Someone reading the template sees at once what inputs it expects.
Failing loudly on missing values
Template.substitute raises a KeyError if a variable has no value. This is the behavior you want. A prompt that silently contains the literal text $style is sent to the model, costs money, and returns a poor answer that is hard to trace.
from string import Template
template = Template("Summarize the following text in $style style:\n\n$text")
try:
template.substitute(style="concise")
except KeyError as error:
print(f"Missing variable: {error}")This prints Missing variable: 'text'.
The method safe_substitute does the opposite. It leaves unknown placeholders in the output instead of raising an error.
Choosing a template syntax
string.Template is not the only option. The right choice depends on how complex your prompts are.
| Option | Variable syntax | Strengths | Limits |
|---|---|---|---|
| `string.Template` | `$name` | Standard library, simple, few surprises with braces | No loops or conditions |
| `str.format` | `{name}` | Standard library, familiar | Literal braces must be doubled, which is awkward for JSON examples in prompts |
| Jinja2 | `{{ name }}` | Loops, conditions, filters | Extra dependency, more room for logic in the template |
Prompts often contain JSON examples with many { and } characters. That is one reason $name syntax is a practical default: braces need no escaping. If you need to write a literal dollar sign, use $$.
What should be a variable
A useful rule: make a part a variable if it changes between calls, and leave it fixed if it defines the task.
- Variable: the user's text, the document to summarize, the target language, the output style.
- Fixed: the role description, the output format rules, the safety instructions.
Too few variables make the template inflexible. Too many make it hard to read, and the fixed instructions get lost among placeholders.
Wrapping a template for reuse
Placing the template and its rendering in one small function gives callers a clear interface.
from string import Template
SUMMARIZE = Template(
"Summarize the following text in $style style.\n"
"If the text is under 50 words, answer in one sentence.\n\n"
"$text"
)
def summarize_prompt(style, text):
return SUMMARIZE.substitute(style=style, text=text)
print(summarize_prompt("concise", "Cats sleep a lot."))Callers now pass only values. The wording lives in one place, so changing it affects every use at once.
Common errors
- Writing
$text.or$text_summarywhen you meant$textfollowed by other characters. The parser reads identifier characters greedily, so use${text}_summaryto end the name explicitly. - Forgetting
$$for a literal dollar sign, which raises aValueErrorfor an invalid placeholder. - Using
safe_substituteand sending an unfilled placeholder to the model. - Passing a value that is not a string, such as
None, and getting the textNonein the prompt.
Exercise
A template contains the text "Price: $5 for $item". Calling Template(...).substitute(item="tea") raises a ValueError. Why, and how do you fix it?
Show answer
In string.Template, $5 is parsed as a placeholder, but 5 is not a valid identifier, so Python raises ValueError. Write $$5 to produce a literal dollar sign, giving "Price: $5 for $item".
Exercise
Why is substitute usually a better choice than safe_substitute for prompts?
Show answer
substitute raises a KeyError when a variable has no value, so the mistake is caught before the model call. safe_substitute leaves the placeholder in the text, and the model receives a broken prompt.