This guide explains str.format Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
str.format() replaces brace-based placeholders in a format string with arguments. Positional and named fields allow templates to be reused with different values; format specifications can control decimals, alignment and more.
When You Would Use This
Produce a clear receipt line from two values.
Step-by-Step Example
receipt_template = "{product}: ${price:.2f}"
print(receipt_template.format(product="Notebook", price=3.5))
print(receipt_template.format(product="Pencil", price=0.75))
How the Example Works
The placeholder names map to keyword arguments. :.2f formats each numeric price to two decimal places without changing the stored value.
Example Output
Notebook: $3.50
Pencil: $0.75
Try It Yourself
Add a {quantity} field and calculate an extended price before formatting the receipt.
Common Beginner Mistakes
- Forgetting to double literal braces as
{{and}}. - Assuming placeholders can execute arbitrary Python statements.
- Building SQL from user values with string formatting rather than prepared parameters.
Key Takeaways
str.format()replaces brace-based placeholders in a format string with arguments.- The placeholder names map to keyword arguments.
- Avoid this mistake: Forgetting to double literal braces as
{{and}}.