Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Implement a simple template formatter

Create a minimal named-placeholder template formatter supporting escaped braces.

Python practice25 minString PatternsAdvancedLast updated March 18, 2026

Problem statement

Implement simple_template(template, mapping) that returns a string where placeholders of the form {key} are replaced by str(mapping[key]) when the key exists in mapping. If a key is not present in mapping, leave the placeholder unchanged (i.e., keep {key} in output). Support literal brace escapes: replace '{{' with '{' and '}}' with '}'. Unmatched single braces (a '{' without a subsequent '}') should raise a ValueError. Keys may be empty ("{}") and should be looked up using the empty-string key if present in mapping.

Task

Build a function to replace placeholders like {name} with values from a mapping and handle escaped braces {{ and }}.

Examples

Basic replacement

Input

simple_template('Hello {name}!', {'name': 'Alice'})

Output

'Hello Alice!'

The placeholder {name} is replaced with 'Alice'.

Escaped braces

Input

simple_template('{{greet}} {who}', {'who': 'world'})

Output

'{greet} world'

Double braces produce a single literal brace in output.

Input format

template (string), mapping (dict of keys to values).

Output format

A string with placeholders replaced by mapping values (converted to str) and escaped braces handled.

Constraints

Do not use external libraries. Implement parsing manually or using only the Python standard library.

Samples

Sample 1

Input

simple_template('X{a}Y{b}Z', {'a': 1, 'b': 2})

Output

'X1Y2Z'

Multiple placeholders are replaced in sequence.