Python String Formatting Challenge
String formatting is a fundamental skill in Python for creating dynamic and readable output. This challenge will test your ability to construct strings by embedding variables and values in a structured way. Mastering string formatting is crucial for tasks ranging from logging and error reporting to generating dynamic web content.
Problem Description
Your task is to implement a function that takes a template string and a dictionary of values, and then formats the string by replacing placeholders with the corresponding values from the dictionary.
The template string will contain placeholders enclosed in curly braces {}. These placeholders will be simple keys that match the keys in the provided dictionary.
Key Requirements:
- Placeholder Replacement: All occurrences of
{key}in the template string should be replaced by the string representation of the value associated withkeyin the input dictionary. - Type Conversion: Values from the dictionary can be of various types (integers, floats, strings, booleans, etc.). Ensure they are correctly converted to their string representation before insertion.
- Missing Keys: If a placeholder
{key}exists in the template butkeyis not present in the dictionary, raise aKeyError. - Empty Dictionary: If the dictionary is empty but the template contains placeholders, a
KeyErrorshould be raised. - No Placeholders: If the template string contains no placeholders, it should be returned as-is, even if the dictionary is not empty.
Expected Behavior:
The function should return a new string with all placeholders replaced. The original template string and dictionary should remain unchanged.
Edge Cases to Consider:
- Placeholders with numerical keys.
- Placeholders with keys containing special characters (though for this challenge, assume valid dictionary keys).
- Empty template string.
- Template string with consecutive placeholders.
Examples
Example 1:
Input:
template = "Hello, {name}! You are {age} years old."
data = {"name": "Alice", "age": 30}
Output:
"Hello, Alice! You are 30 years old."
Explanation:
The placeholder "{name}" is replaced with "Alice" from the dictionary.
The placeholder "{age}" is replaced with "30" (converted from integer 30) from the dictionary.
Example 2:
Input:
template = "Item: {item_name}, Price: ${price:.2f}"
data = {"item_name": "Laptop", "price": 1200.50}
Output:
"Item: Laptop, Price: $1200.50"
Explanation:
"{item_name}" is replaced with "Laptop".
"{price:.2f}" indicates the value associated with "price" should be formatted as a float with 2 decimal places. The value 1200.50 is formatted to "1200.50".
Example 3:
Input:
template = "User ID: {user_id}"
data = {}
Output:
Raises KeyError: "user_id"
Explanation:
The template contains a placeholder "{user_id}", but the dictionary is empty and does not contain the key "user_id".
Example 4:
Input:
template = "Status: {status}"
data = {"message": "Success"}
Output:
Raises KeyError: "status"
Explanation:
The template contains a placeholder "{status}", but the dictionary only contains the key "message".
Example 5:
Input:
template = "This is a plain string."
data = {"key": "value"}
Output:
"This is a plain string."
Explanation:
The template has no placeholders, so it is returned as-is.
Constraints
- The template string can contain alphanumeric characters, spaces, punctuation, and placeholders.
- Dictionary keys will be strings.
- Dictionary values can be of any Python type that has a standard string representation (e.g., int, float, str, bool, list, tuple, dict).
- Placeholders will follow the format
{key}or{key:format_spec}wherekeyis a valid dictionary key andformat_specis a valid Python format specification (e.g.,.2f,>10). - The function should complete within a reasonable time, typically O(N) where N is the length of the template string.
Notes
This challenge is designed to help you understand and implement a custom string formatting mechanism. While Python's built-in str.format() method already provides this functionality, this exercise is about building it from scratch to understand the underlying principles.
Consider how you will iterate through the template string, identify placeholders, look up values in the dictionary, handle potential errors, and construct the final output string. You might find regular expressions helpful for parsing the placeholders, or you could devise a manual parsing approach. Remember to handle the format specifications within the placeholders as well.