0PricingLogin
AI Prompt Engineering · Lesson

Variable Substitution Techniques

f-strings, .format(), and template libraries for prompt rendering.

Four Python Approaches to Template Rendering

Python offers several ways to render prompt templates with variable substitution. Each has strengths and trade-offs:

  • f-strings — inline, immediate, no imports needed
  • str.format() — named placeholders, validation-friendly
  • string.Template — safe dollar-sign substitution, partial filling supported
  • Jinja2 — full templating engine: conditionals, loops, filters, inheritance

Choosing the right approach depends on template complexity, team skills, and whether you need advanced features like conditionals and loops.

Approach 1: Python f-strings

F-strings are the simplest approach for prompt templates where all variables are available at render time:

import openai

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

def generate_linkedin_post(company, topic, tone, word_count):
    prompt = (
        f'Write a LinkedIn post for {company} about {topic}. '
        f'Tone: {tone}. '
        f'Length: {word_count} words. '
        'Professional but conversational. '
        'End with one question to engage readers. '
        'No hashtags. Active voice.'
    )

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

print(generate_linkedin_post(
    company='DataStream Analytics',
    topic='how AI is changing data pipelines',
    tone='enthusiastic but grounded',
    word_count=180
))

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