0Pricing
AI Prompt Engineering · 课时

创建填空模式

在 Python 中使用 {{variable}} 占位符和字符串替换

创建填空模式 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

占位符约定

填空式提示词模式使用占位符标记提示词中将在发送给模型之前替换为实际值的部分。

最常见的占位符约定是双大括号:{{variable_name}}。这种约定易于阅读,不太可能意外出现在普通文本中,并且受到各种模板库的广泛支持。

您还会遇到其他约定:单大括号 {variable}、尖括号 <variable>以及全大写变量。请选择一种并保持一致。

基本占位符替换

最简单的填空模式是直接替换字符串:

模板:“为 {{audience}} 撰写一篇关于 {{product}} 的、长度为 {{word_count}} 字的说明。”

已填充:“面向小型企业主,撰写一篇 150 字的 TaskFlow Pro 产品介绍。”

替换会在字符串发送给模型之前完成——模型看到的是一个整洁、完整的提示词,其中没有占位符标记。占位符属于预处理步骤,而不是由模型自行处理的内容。

常见占位符类别

请使用涵盖大多数使用场景的标准占位符类别来构建模板:

  • {{customer_name}} — 收件人或主题名称
  • {{product}} — 要撰写其相关内容的产品、服务或主题
  • {{tone}} — 例如专业、随意、紧急、热情
  • {{audience}} — 内容面向的对象
  • {{word_count}} — 目标长度
  • {{format}} — 项目符号、段落、编号列表
  • {{context}} — 此次具体实例的背景信息

在不同模板中保持一致的命名方式,可以让您的模板库更易于查找,并减少错误。

Python 字符串 format 替换

Python 内置的字符串 .format() 方法可以使用 {variable} 语法轻松填充占位符:

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 字符串方法

Python f 字符串提供了内联替换语法,一些开发者更喜欢这种方式,因为它具有较好的可读性:

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'
))

处理占位符中的特殊字符

一个常见错误是:用户提供的值如果包含花括号、引号或换行符,可能会破坏字符串替换。

防御性处理方法:

  • 在替换前清理输入——如有需要,移除或转义特殊字符
  • 对多行模板使用三引号字符串,以安全处理换行符
  • 当变量值本身包含花括号(例如代码)时,请使用将变量值视为字面量的方法(Jinja2 对此处理得很好)

请始终使用边界情况输入测试模板:空字符串、包含引号的字符串、包含换行符的字符串以及非常长的字符串。

模板中的默认值

并非所有变量都必须是必填项。为可选参数设置默认值,可以让模板更加灵活:

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'))

多块模板

复杂的提示词可能包含多个变量块——一个系统提示词块和一个用户消息块,每个块都有自己的占位符:

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

渲染前验证占位符

在发送提示词之前,请始终验证所有必需的占位符都已填充。缺少占位符意味着模型会收到类似 {{product}} 的字面文本,并可能生成异常的输出:

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'}}

条件模板块

有时,只有在提供了某个变量时,模板中的某个部分才应显示。您可以在 Python 中通过有条件地构建字符串来实现这一点:

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'
))

枚举选择变量

有些模板变量应限制为一组固定的有效选项。请通过枚举式验证来执行这一限制:

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

知识检查:填空模式

您有以下模板:'Write a {tone} email to {recipient} about {topic}. Length: {word_count} words.'

您这样调用它:tone='formal', recipient='the team', word_count=100,但忘记了 topic 参数。

会发生什么?

回顾:创建填空模式

填空式提示词模式使用占位符({{variable}}、{variable} 或类似形式)标记可复用模板中的可变部分。Python 的 .format() 和 f 字符串是最常见的替换机制。

最佳实践包括:在渲染前验证所有必需的占位符,为可选变量设置默认值,限制枚举变量的取值,并以防御性方式处理边界情况输入(空字符串、特殊字符)。

下一课中,您将探索 Jinja2 和 Python 的 string.Template,以满足更强大的变量替换需求。

常见问题解答

「创建填空模式」课时是免费的吗?

是的 — 「创建填空模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「创建填空模式」这节课中我会学到什么?

在 Python 中使用 {{variable}} 占位符和字符串替换 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「创建填空模式」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 什么是提示模板
  2. 创建填空模式
  3. 变量替换技巧
  4. 在不同任务间复用模板
← 返回 AI Prompt Engineering