Prompt templates keep wording the same for every request: code fills in the placeholders.
What to build
A program that fills the {name} placeholders of a template, or reports the names that have no value.
Requirements
- If every placeholder has a value, print the template with each
{name}replaced by its value. - Otherwise print only
missing:followed by the names without a value, sorted and without repeats, separated by,.
Input
Line 1: the template. Line 2: n. Then n lines of the form name=value.
Output
One line.
Constraints
Names use letters, digits and underscores. A value does not contain a brace.
Example
Input:
Hello {name}, welcome to {place}.
2
name=Ana
place=Dhaka
Output:
Hello Ana, welcome to Dhaka.
Why it works
The pattern finds every placeholder, a dictionary maps each name to its value, and checking for gaps first stops a half-filled prompt from being sent to the model.
Examples
Hello {name}, welcome to {place}.
2
name=Ana
place=Dhaka
Hello Ana, welcome to Dhaka.
Translate to {lang}: {text}
2
lang=French
text=good morning
Translate to French: good morning
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Find the placeholders with the pattern `\{(\w+)\}` from the `re` module.
Hint 2
Collect the names that have no value first; if there are any, print only the `missing:` line.
Solution
Show one correct solution (try it yourself first)
import re
template = input()
n = int(input())
values = {}
for _ in range(n):
key, _, val = input().partition("=")
values[key] = val
names = re.findall(r"\{(\w+)\}", template)
missing = sorted({x for x in names if x not in values})
if missing:
print("missing: " + ", ".join(missing))
else:
print(re.sub(r"\{(\w+)\}", lambda m: values[m.group(1)], template))