This guide explains str.format() vs f-Strings vs Percent Formatting through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
f-strings, .format() and percent formatting all insert values into strings. f-strings are concise for known expressions; .format() handles reusable templates; percent formatting often appears in older code.
When You Would Use This
Generate the same notice in three styles.
Step-by-Step Example
person_name = "Morgan"
print(f"Hello, {person_name}!")
print("Hello, {}!".format(person_name))
print("Hello, %s!" % person_name)
How the Example Works
All three lines display Hello, Morgan!. The difference is the source syntax and how placeholders are supplied.
Example Output
Hello, Morgan!
Hello, Morgan!
Hello, Morgan!
Try It Yourself
Write a two-field status message with f-string and .format().
Common Beginner Mistakes
- Passing percent placeholders through an f-string as if they were braces.
- Assuming
.format()evaluates arbitrary Python expressions inside placeholders. - Building SQL queries with string formatting instead of parameterized queries.
Key Takeaways
- f-strings,
.format()and percent formatting all insert values into strings. - All three lines display
Hello, Morgan!. - Avoid this mistake: Passing percent placeholders through an f-string as if they were braces.