Python f-strings
In this page:
Introduction to f-strings
An f-string is created by prefixing a string literal with f or F, which tells Python to evaluate any {expression} inside it at runtime and splice the result directly into the text — f"Hello, {name}" is both shorter and clearer than the equivalent .format() call.
Example: Introduction to f-strings
name = "Alex"
print(f"Hello, {name}")
Evaluating Expressions
Because the braces in an f-string hold live Python expressions, not just variable names, you can write f"{a + b}" or f"{is_valid and count > 0}" and Python evaluates the math or logic on the spot before inserting the result.
Example: Evaluating Expressions
a, b = 2, 3
print(f"{a + b}")
count = 5
print(f"{count > 0}")
Formatting Floats
Adding a format spec after a colon inside the braces, like f"{price:.2f}", controls numeric display the same way .format() does — rounding, padding, and separators are all available using the same mini-language.
Example: Formatting Floats
price = 19.999
print(f"{price:.2f}")
Calling Methods and Functions
You can call functions and string methods directly inside the braces — f"{name.upper()}" — since the interpreter simply evaluates whatever expression sits between { and } before converting it to text.
Example: Calling Methods and Functions
name = "alex"
print(f"{name.upper()}")
Alignments and Debugging
The debugging shorthand f"{value=}" prints both the expression's source text and its current value, which is a fast way to inspect a variable's state while troubleshooting without writing a separate print("value:", value) line.
Example: Alignments and Debugging
value = 42
print(f"{value=}")
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators