How to Format Strings with Named Placeholders in Python

Format a template string using named placeholders with the str.format() method and a dictionary.

Easy Python 3.6+ Aug 9, 2026 Strings & text 15 views 0 copies

Python code

10 lines
Python 3.6+
def 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

stdout
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

  1. Use f-strings with manual dictionary access: `f"Hello {data['name']}"`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.