How to Format Strings with Named Placeholders in Python
Format a template string using named placeholders with the str.format() method and a dictionary.
Python code
10 linesdef format_named(template, data):
"""Format a template string using named placeholders."""
return template.format(**data)
if __name__ == "__main__":
template = "Hello {name}, you are {age} years old and live in {city}."
data = {"name": "Alice", "age": 30, "city": "London"}
result = format_named(template, data)
print(result)
Output
Hello Alice, you are 30 years old and live in London.
How it works
The str.format() method supports named placeholders by using {name} inside the template. By unpacking the dictionary with **data, each key becomes a keyword argument to format(), which replaces the placeholders with corresponding values. This approach keeps the template readable and decouples the data from the formatting logic. It's safe as long as all placeholders exist in the dictionary; otherwise, a KeyError is raised. The method is part of the standard library, so no external packages are needed.
Common mistakes
- Forgetting to use `**` when passing the dictionary, causing a TypeError
- Not accounting for missing keys, which raises KeyError
- Using uppercase `Format` instead of `format`
- Mixing positional and named placeholders in a confusing way
Variations
- Use f-strings with manual dictionary access: `f"Hello {data['name']}"`
- Use `string.Template` with `$placeholder` syntax for simpler substitution
Real-world use cases
- Generating personalized email content from user profile data dictionaries.
- Building SQL query strings with safe parameter substitution for logging or templates.
- Producing configuration-based report templates where field names vary per client.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.