0Pricing
AI Prompt Engineering · Lesson

Creating Fill-in-the-Blank Patterns

Using {{variable}} placeholders and string substitution in Python.

Creating Fill-in-the-Blank Patterns is a free AI Prompt Engineering lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Prompt Engineering learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Placeholder Convention

A fill-in-the-blank prompt pattern uses placeholders to mark the parts of a prompt that will be substituted with real values before being sent to the model.

The most common placeholder convention is double curly braces: {{variable_name}}. This convention is easy to read, unlikely to appear in normal text accidentally, and widely supported by templating libraries.

Other conventions you will encounter: single curly braces {variable}, angle brackets <variable>, and ALL_CAPS variables. Choose one and be consistent.

Basic Placeholder Substitution

The simplest fill-in-the-blank pattern is direct string substitution:

Template: "Write a {{word_count}}-word description of {{product}} for {{audience}}."

Filled: "Write a 150-word description of TaskFlow Pro for small business owners."

The substitution happens before the string is sent to the model — the model sees a clean, complete prompt with no placeholder markers. Placeholders are a pre-processing step, not something the model itself handles.

Common Placeholder Categories

Build your templates using standard placeholder categories that cover most use cases:

  • {{customer_name}} — recipient or subject name
  • {{product}} — the product, service, or topic being written about
  • {{tone}} — e.g., professional, casual, urgent, enthusiastic
  • {{audience}} — who the content is for
  • {{word_count}} — target length
  • {{format}} — bullet points, paragraphs, numbered list
  • {{context}} — background information specific to this instance

Consistent naming across templates makes your library easier to navigate and reduces errors.

Python String Format Substitution

Python's built-in string .format() method is a simple way to fill placeholders using {variable} syntax:

import openai

client = openai.OpenAI(api_key='sk-...')

EMAIL_TEMPLATE = '''Write a follow-up email from {sender_name} to {recipient_name}.
Context: {context}
Tone: {tone}
Length: {word_count} words.
Include a clear call to action: {cta}.
Do not mention competitors. Active voice. No bullet points.'''

def generate_email(sender, recipient, context, tone, word_count, cta):
    prompt = EMAIL_TEMPLATE.format(
        sender_name=sender,
        recipient_name=recipient,
        context=context,
        tone=tone,
        word_count=word_count,
        cta=cta
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.choices[0].message.content

result = generate_email(
    sender='Sarah Chen',
    recipient='Mr. Patel',
    context='We met at the DevConf conference last week and discussed API integration.',
    tone='warm and professional',
    word_count=120,
    cta='Schedule a 20-minute demo call'
)
print(result)

Python f-string Approach

Python f-strings provide an inline substitution syntax that some developers prefer for its readability:

import openai

client = openai.OpenAI(api_key='sk-...')

def generate_product_description(product, audience, tone, word_count, key_benefit):
    prompt = (
        f'Write a product description for {product}, designed for {audience}. '
        f'Tone: {tone}. '
        f'Length: {word_count} words. '
        f'Lead with this key benefit: {key_benefit}. '
        'Active voice. No bullet points. No pricing mentions.'
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[{'role': 'user', 'content': prompt}]
    )
    return response.choices[0].message.content

print(generate_product_description(
    product='FocusFlow, a time-blocking productivity app',
    audience='freelancers and independent consultants',
    tone='energetic and practical',
    word_count=150,
    key_benefit='Reclaim two hours every day by blocking distractions automatically'
))

Handling Special Characters in Placeholders

A common bug: user-provided values that contain curly braces, quotes, or newlines can break string substitution.

Defensive approaches:

  • Sanitize inputs before substitution — strip or escape special characters if needed
  • Use triple-quoted strings for multi-line templates to handle newlines safely
  • When the variable value itself contains curly braces (e.g., code), use an approach that treats the variable value as literal (Jinja2 handles this well)

Always test your template with edge case inputs: empty strings, strings with quotes, strings with newlines, and very long strings.

Default Values in Templates

Not all variables need to be required. Templates become more flexible with default values for optional parameters:

def build_prompt(product, audience, tone='professional and friendly', word_count=200, format_style='prose'):
    format_instruction = {
        'prose': 'Write in continuous paragraphs. No bullet points.',
        'bullets': 'Use bullet points. Each point is one sentence.',
        'numbered': 'Use a numbered list. Each item is one sentence.'
    }.get(format_style, 'Write in continuous paragraphs.')

    return (
        f'Write a description of {product} for {audience}. '
        f'Tone: {tone}. '
        f'Length: {word_count} words. '
        f'{format_instruction} '
        'Active voice. No competitor mentions.'
    )

# Minimal call — uses all defaults
print(build_prompt('Notion', 'students'))

# Full call — overrides defaults
print(build_prompt('Notion', 'students', tone='casual', word_count=100, format_style='bullets'))

Multi-Block Templates

Complex prompts may have multiple variable blocks — a system prompt block and a user message block, each with their own placeholders:

SYSTEM_TEMPLATE = 'You are a {role} writing for {company}. Your audience is {audience}. Style: {style}.'

USER_TEMPLATE = 'Write a {content_type} about {topic}. Length: {word_count} words. Deadline tone: {urgency}.'

import openai

client = openai.OpenAI(api_key='sk-...')

def generate(role, company, audience, style, content_type, topic, word_count, urgency):
    system_msg = SYSTEM_TEMPLATE.format(
        role=role, company=company, audience=audience, style=style
    )
    user_msg = USER_TEMPLATE.format(
        content_type=content_type, topic=topic,
        word_count=word_count, urgency=urgency
    )

    response = client.chat.completions.create(
        model='gpt-4o-mini',
        messages=[
            {'role': 'system', 'content': system_msg},
            {'role': 'user', 'content': user_msg}
        ]
    )
    return response.choices[0].message.content

Validating Placeholders Before Rendering

Always validate that all required placeholders are filled before sending the prompt. A missing placeholder means the model receives literal text like {{product}} and may produce bizarre output:

import re

def validate_template(template_str, provided_vars):
    required = set(re.findall(r'\{\{(\w+)\}\}', template_str))
    missing = required - set(provided_vars.keys())

    if missing:
        raise ValueError(f'Missing required template variables: {missing}')

    return True

template = 'Write a {{word_count}}-word {{tone}} description of {{product}} for {{audience}}.'
vars_provided = {'word_count': 150, 'tone': 'friendly', 'product': 'TaskFlow'}

try:
    validate_template(template, vars_provided)
except ValueError as e:
    print(f'Template error: {e}')
    # Output: Template error: Missing required template variables: {{'audience'}}

Conditional Template Blocks

Sometimes a template section should only appear if a variable is provided. You can implement this in Python with conditional string building:

def build_report_prompt(topic, audience, word_count, include_recommendations=False, cta=None):
    prompt = f'Write a report on {topic} for {audience}. Length: {word_count} words. Active voice.'

    if include_recommendations:
        prompt += ' End with a numbered list of 3 specific recommendations.'

    if cta:
        prompt += f' Close with this call to action: {cta}'

    return prompt

# Without optional sections
print(build_report_prompt('cloud cost optimization', 'engineering managers', 400))

# With optional sections
print(build_report_prompt(
    topic='cloud cost optimization',
    audience='engineering managers',
    word_count=600,
    include_recommendations=True,
    cta='Book a cost audit with our team at cloudcost.io'
))

Enumerated Choice Variables

Some template variables should be constrained to a fixed set of valid options. Enforce this with an enum-style validation:

VALID_TONES = ['professional', 'casual', 'urgent', 'empathetic', 'enthusiastic']
VALID_FORMATS = ['prose', 'bullets', 'numbered', 'table']

def generate_content(topic, tone, format_style, word_count):
    if tone not in VALID_TONES:
        raise ValueError(f'Invalid tone: {tone}. Choose from: {VALID_TONES}')
    if format_style not in VALID_FORMATS:
        raise ValueError(f'Invalid format: {format_style}. Choose from: {VALID_FORMATS}')

    format_map = {
        'prose': 'continuous paragraphs, no lists',
        'bullets': 'bullet points',
        'numbered': 'numbered list',
        'table': 'a markdown table'
    }

    prompt = (f'Write about {topic} in {tone} tone. '
              f'Format: {format_map[format_style]}. '
              f'Length: {word_count} words. Active voice.')

    return prompt

Knowledge Check: Fill-In-The-Blank Patterns

You have this template: 'Write a {tone} email to {recipient} about {topic}. Length: {word_count} words.'

You call it with: tone='formal', recipient='the team', word_count=100 — but forget the topic parameter.

What happens?

Recap: Creating Fill-In-The-Blank Patterns

Fill-in-the-blank prompt patterns use placeholders ({{variable}}, {variable}, or similar) to mark the variable parts of a reusable template. Python's .format() and f-strings are the most common substitution mechanisms.

Best practices: validate all required placeholders before rendering, use default values for optional variables, constrain enumerated variables, and handle edge case inputs (empty strings, special characters) defensively.

In the next lesson, you will explore Jinja2 and Python's string.Template for more powerful variable substitution needs.

Frequently asked questions

Is the “Creating Fill-in-the-Blank Patterns” lesson free?

Yes — the full text of “Creating Fill-in-the-Blank Patterns” is free to read here on the web, and the AI Prompt Engineering course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Prompt Engineering course, upgrade to CoddyKit PRO.

What will I learn in “Creating Fill-in-the-Blank Patterns”?

Using {{variable}} placeholders and string substitution in Python. You practise AI Prompt Engineering with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Prompt Engineering?

No prior experience is required. AI Prompt Engineering on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Creating Fill-in-the-Blank Patterns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Prompt Engineering lesson?

Yes. Every AI Prompt Engineering lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. What Is a Prompt Template?
  2. Creating Fill-in-the-Blank Patterns
  3. Variable Substitution Techniques
  4. Reusing Templates Across Tasks
← Back to AI Prompt Engineering