easy +10 pts

Replace template variables

Expand template placeholders using a dictionary of values, with missing variables left unchanged.

Write a function `replace_template(template, variables)` that takes a string `template` and a dictionary `variables` mapping variable names to string values. The function must return a new string where every occurrence of `{{name}}` in the template is replaced by the corresponding value from `variables`. Variable names consist only of lowercase letters, digits, and underscores, and appear between double curly braces. If a variable name in the template is not present in `variables`, the placeholder `{{name}}` must be left unchanged in the output. All occurrences of a known variable must be replaced. The function should not modify the input dictionary or the template.

Constraints

The template length is between 0 and 1000 characters. The number of keys in variables is between 0 and 100. Variable names are non-empty. Expected time complexity: O(len(template) + total length of replacements).

Example

['>>> replace_template("Hello {{name}}!", {"name": "World"})\n"Hello World!"', '>>> replace_template("Hi {{name}} and {{name}}", {"name": "Alex"})\n"Hi Alex and Alex"', '>>> replace_template("{{greeting}}, {{name}}!", {"name": "Bob", "greeting": "Hello"})\n"Hello, Bob!"', '>>> replace_template("{{unknown}} value", {"known": "x"})\n"{{unknown}} value"', '>>> replace_template("No placeholders", {})\n"No placeholders"']
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a while loop with find to locate the '{{' and the matching '}}'.
Extract the variable name by slicing between the braces.
Build the result by appending the replacement when the name is in the dictionary, otherwise keep the original placeholder.
Remember to advance the search index past the closing brace to avoid infinite loops.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.