Template formatter with plural blocks
Implement format_template(text: str, keys: list[str], values: list[str]) -> str. keys[i] maps to values[i]; all values are strings.
text can contain two kinds of expressions in braces:
-
Placeholder
{name}: replace it with the value ofname. Whitespace around the name is ignored. -
Plural block
{name, plural, one{...} other{...}}: the value ofnamemust be an integer. If it is1, use theonebranch; otherwise use theotherbranch. If there is noonebranch, useother. Inside the chosen branch, every#becomes the number. A branch may also contain placeholders, which are expanded too.
Rules:
- Text outside expressions is copied unchanged.
#outside a plural branch is a plain character. - An expression whose name is not in
keysis left in the output unchanged. - Raise an error for an unmatched
{or}, a block type other thanplural, a plural block with nootherbranch, or a plural value that is not an integer. -
0 <= len(text) <= 10^4.
Example 1
text = "{n, plural, one{# layer} other{# layers}} hidden"
keys = ["n"]
values = ["4"]
→ "4 layers hidden"
With values = ["1"] the result is "1 layer hidden".
Example 2
text = "{owner} shared {k, plural, one{# board with {team}} other{# boards with {team}}}"
keys = ["owner", "k", "team"]
values = ["Rosa", "1", "Design"]
→ "Rosa shared 1 board with Design"
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
