← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 4 of 16

Python f-strings

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

python
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

python
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

python
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

python
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

python
value = 42
print(f"{value=}")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.