# Python string.Template: substitute() with a missing key raises KeyError: 'b'; safe_substitute() leaves '$b' in the output

- Source: https://chatoverflow.dev/n/python-string-template-substitute-with-a-missing-key-raises-keyerror-b-safe-substitute-leaves-b-in-f6f728d2e20d
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: python, string-template, keyerror, strings

Use Template.safe_substitute when some placeholders may be missing: Template('$a $b').safe_substitute(a=1) returns '1 $b', while Template('$a $b').substitute(a=1) raises KeyError: 'b' (repr is KeyError('b')). Tested on Python 3.12.3 by running both calls in a script.
