An Introduction to Python f-
strings
A modern approach to string
formatting
What are f-strings?
• Definition: Formatted String Literals, introduced in
Python 3.6.
• Purpose: Concise, readable, and efficient way to
embed Python expressions inside strings.
• Syntax: Prefix a string with f (or F).
• Key Feature: Use curly braces {} to insert
expressions.
Basic Syntax
Simple variables:
• name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
Expressions and function calls:
• x = 10
y=5
print(f"The sum of {x} and {y} is {x + y}.")
• print(f"Name in uppercase: {[Link]()}.")
Advanced Formatting
Format specifiers: Use ':' after the expression.
f"Average: {84.0:.2f}" -> Average: 84.00
f"Value: {12345678:,d}" -> Value: 12,345,678
f"ID: {7:03d}" -> ID: 007
Alignment: f"{'Padded':<10}" (left align),
f"{'Padded':>10}" (right align)
Debugging with f-strings
• Self-documenting expressions (Python 3.8+).
• Add '=' inside curly braces to display variable name and
value.
• Example:
• debug_value = 42
• print(f"{debug_value=}")
• Output: debug_value=42
f-strings vs. Older Methods
• Feature f-strings [Link]() % Operator
• Readability High Medium Low
• Conciseness High Medium Low
• Speed Fastest Slower Slowest
• Syntax f"text {var}" "text {}".format(var)
"text %s" % var
• Expressions Yes No No
• Introduction Python 3.6 Python 2.6 Legacy
Why use f-strings?
• Improved readability – easier to understand
& maintain.
• Reduced errors – no mismatched
placeholders.
• Better performance – faster than other
methods.
• Powerful formatting – built-in specifiers.
• Modern standard – recommended way in
Python.
Conclusion
• f-strings are a powerful and modern tool
for string formatting in Python.
• They allow embedding expressions directly
into strings.
• Concise syntax, better performance, and
debugging features make them the clear
choice for Python programmers.