0Pricing
AI Prompt Engineering · 강의

빈칸 채우기 패턴 만들기

Python에서 {{variable}} 자리 표시자와 문자열 치환을 사용하는 방법을 익힙니다.

빈칸 채우기 패턴 만들기은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Prompt Engineering 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

자리 표시자 규칙

빈칸 채우기 프롬프트 패턴은 자리 표시자를 사용하여 모델에 보내기 전에 실제 값으로 대체할 프롬프트의 부분을 표시합니다.

가장 일반적인 자리 표시자 규칙은 중괄호 두 개를 사용하는 것입니다: {{variable_name}}. 이 규칙은 읽기 쉽고 일반적인 텍스트에 실수로 나타날 가능성이 낮으며 템플릿 라이브러리에서 널리 지원됩니다.

다음과 같은 다른 규칙도 사용됩니다: 중괄호 하나 {variable}, 꺾쇠괄호 <variable>, 대문자로 작성한 변수. 하나를 선택하고 일관되게 사용하십시오.

기본 자리 표시자 치환

가장 단순한 빈칸 채우기 패턴은 문자열을 직접 치환하는 방식입니다:

템플릿: "{{word_count}}단어 분량의 {{product}}에 대한 설명을 {{audience}}을 대상으로 작성하세요."

입력 후: "소규모 사업주를 대상으로 TaskFlow Pro에 대한 150단어 설명을 작성하세요."

치환은 문자열을 모델에 보내기 전에 이루어지므로 모델은 자리 표시자 표식이 없는 깔끔하고 완전한 프롬프트를 받습니다. 자리 표시자는 전처리 단계에서 처리되며 모델 자체가 처리하는 것이 아닙니다.

일반적인 자리 표시자 범주

대부분의 사용 사례를 포괄하는 표준 자리 표시자 범주를 사용하여 템플릿을 구성하세요:

  • {{customer_name}} — 수신자 또는 대상 이름
  • {{product}} — 설명의 대상이 되는 제품, 서비스 또는 주제
  • {{tone}} — 예: 전문적인 말투, 편안한 말투, 긴급한 말투, 열정적인 말투
  • {{audience}} — 콘텐츠의 대상
  • {{word_count}} — 목표 길이
  • {{format}} — 글머리 기호 목록, 단락, 번호 매기기 목록
  • {{context}} — 해당 사례에 특화된 배경 정보

템플릿 전체에서 이름을 일관되게 사용하면 라이브러리를 더 쉽게 탐색할 수 있고 오류도 줄어듭니다.

파이썬 문자열 형식 치환

파이썬에 내장된 문자열 .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)

파이썬 f 문자열 방식

파이썬 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'
))

자리 표시자의 특수 문자 처리

흔히 발생하는 버그는 중괄호, 따옴표 또는 줄바꿈이 포함된 사용자 제공 값이 문자열 치환을 망가뜨리는 것입니다.

방어적 접근 방법:

  • 치환 전에 입력값을 정제합니다 — 필요하면 특수 문자를 제거하거나 이스케이프합니다
  • 여러 줄 템플릿에는 따옴표 3개로 감싼 문자열을 사용하여 줄바꿈을 안전하게 처리합니다
  • 변수 값 자체에 중괄호가 포함된 경우(예: 코드) 변수 값을 리터럴로 처리하는 방식을 사용합니다(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'}}

조건부 템플릿 블록

때로는 변수가 제공된 경우에만 템플릿의 특정 부분이 나타나야 합니다. 파이썬에서는 조건에 따라 문자열을 구성하여 이를 구현할 수 있습니다:

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}, or similar`)를 사용하여 재사용 가능한 템플릿에서 변하는 부분을 표시합니다. 파이썬의 .format()과 f 문자열이 가장 일반적인 치환 방식입니다.

권장 사항: 렌더링하기 전에 필요한 자리 표시자를 모두 확인하고, 선택적 변수에는 기본값을 사용하며, 열거형 변수의 선택지를 제한하고, 경계 사례 입력값(빈 문자열, 특수 문자)은 방어적으로 처리하세요.

다음 레슨에서는 더 강력한 변수 치환이 필요할 때 사용할 수 있는 Jinja2와 파이썬의 string.Template을 살펴봅니다.

자주 묻는 질문

“빈칸 채우기 패턴 만들기” 강의는 무료인가요?

네 — “빈칸 채우기 패턴 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

“빈칸 채우기 패턴 만들기”에서 뭘 배우나요?

Python에서 {{variable}} 자리 표시자와 문자열 치환을 사용하는 방법을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Prompt Engineering을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Prompt Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“빈칸 채우기 패턴 만들기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Prompt Engineering 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Prompt Engineering 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 프롬프트 템플릿이란 무엇인가
  2. 빈칸 채우기 패턴 만들기
  3. 변수 치환 기법
  4. 여러 작업에서 템플릿 재사용하기
← AI Prompt Engineering(으)로 돌아가기