Python Template Strings — ELI5
You know those Mad Libs games where you have a story with blanks?
“Dear _____, thank you for the _____ gift.”
You fill in the blanks and get a complete sentence.
Python has something almost identical called Template strings.
You write a message with placeholders marked by a dollar sign: $name or ${item}. Then you tell Python what goes in each blank.
"Dear $name, thank you for the $gift."
Fill in name = "Grandma" and gift = "awesome", and you get:
“Dear Grandma, thank you for the awesome gift.”
Why not just use f-strings or .format()?
Those are powerful but a bit too powerful. They can run code inside the placeholders. If someone sneaky puts weird stuff in the blanks, bad things might happen.
Template strings are deliberately simple. They can only do one thing: replace $name with a value. No math, no function calls, no tricks.
That makes them perfect when the template comes from someone you don’t fully trust — like a user filling in their own message, or a config file from an outside source.
When to use them:
- User-supplied message templates
- Config files with variable substitution
- Any time safety matters more than fancy features
When NOT to use them:
- When you control the template yourself (f-strings are faster and more flexible)
- When you need expressions or formatting inside placeholders
One Thing to Remember
Template strings are the safe, simple way to fill in blanks — they do substitution and nothing else, which is exactly the point.
See Also
- Python Csv Processing Learn how Python reads and writes spreadsheet-style CSV files — the universal language of data tables.
- Python Json Handling See how Python talks to the rest of the internet using JSON — the universal language apps use to share information.
- Python Toml Configuration Discover TOML — the config file format Python chose for its own projects, designed to be obvious and impossible to mess up.
- Ci Cd Why big apps can ship updates every day without turning your phone into a glitchy mess — CI/CD is the behind-the-scenes quality gate and delivery truck.
- Containerization Why does software that works on your computer break on everyone else's? Containers fix that — and they're why Netflix can deploy 100 updates a day without the site going down.