Get AI summaries of any video or article — Sign up free
Python Quick Tip: F-Strings - How to Use Them and Advanced String Formatting thumbnail

Python Quick Tip: F-Strings - How to Use Them and Advanced String Formatting

Corey Schafer·
4 min read

Based on Corey Schafer's video on YouTube. If you like this content, support the original creators by watching, liking and subscribing to their content.

TL;DR

Use f-strings (Python 3.6+) to embed variables and expressions directly inside curly braces for clearer string construction.

Briefing

F-strings have become the go-to way to format strings in Python 3.6+ because they make interpolation more readable and more powerful than older approaches like str.format(). Instead of juggling placeholders and a separate format call, an f-string lets variables (and even expressions) be embedded directly inside curly braces, so the final text is easy to scan and maintain.

A typical example uses two variables—first name and last name—to build a sentence like “My name is …”. With str.format(), the code has to match placeholder positions (e.g., {} and {}) to the arguments passed into format(), which becomes harder to reason about as the number of placeholders grows. With an f-string, the variables are written right where they appear in the output: first_name and last_name inside the braces. The result is the same string, but the mapping between value and location is visually obvious.

F-strings also support inline method calls. If the goal is to capitalize names, the formatting can call .upper() directly inside the braces, producing capitalized output without extra temporary variables or concatenation. That same inline capability extends beyond simple variables: dictionary lookups can be performed inside the braces as well, such as person['name'] and person['age'].

That dictionary example introduces a practical gotcha: quoting rules. When an f-string is wrapped in single quotes, inserting single quotes inside the expression (like person['name']) can terminate the string early and trigger a syntax error. The workaround is to use double quotes for the outer f-string so the inner single quotes remain intact.

Beyond interpolation, f-strings can evaluate expressions and perform calculations inline—such as computing 4 * 11 within the braces and printing “four times eleven is equal to 44.” They also enable advanced formatting controls using a colon and format specifiers. For integers, adding :02d pads values with leading zeros to a fixed width (and the width can be increased, e.g., :04d). For floating-point numbers, a precision specifier like :.4f limits output to a set number of digits after the decimal and rounds correctly.

Finally, f-strings can format dates and times, though the transcript uses strftime-style directives embedded in the braces. A datetime object is printed in a human-friendly form by applying codes such as %B for the full month name, %d for the day, and %Y for a four-digit year—turning a raw default datetime representation into something like “January 1st, 1990.” Overall, the takeaway is that f-strings streamline day-to-day formatting while also supporting precision, padding, calculations, and custom date output in a single, readable line.

Cornell Notes

F-strings are Python 3.6+ formatted string literals that place variables and expressions directly inside curly braces, making output easier to read than str.format(). They support inline operations like calling methods (e.g., .upper()) and even performing calculations inside the braces. Dictionary access works too (e.g., person['name']), but quoting matters: using double quotes for the outer f-string avoids syntax errors from inner single quotes. Format specifiers after a colon enable zero-padding for integers (e.g., :02d) and precision control for floats (e.g., :.4f). For dates, f-strings can use strftime directives like %B, %d, and %Y to produce clean, human-readable strings.

Why do f-strings tend to be more readable than str.format() when building sentences with multiple placeholders?

With str.format(), placeholders like {} must be matched to arguments passed into format(), which forces readers to cross-check positions. In an f-string, the variable names appear directly inside the curly braces at the exact point they appear in the output, so the mapping from value to location is visible in one pass.

How can an f-string capitalize values without extra variables?

Method calls can be placed inside the braces. For example, first_name.upper() and last_name.upper() produce capitalized output directly within the formatted string, keeping the code compact and readable.

What’s the common syntax error when formatting dictionary values inside an f-string, and how is it fixed?

If the f-string uses single quotes and the dictionary lookup also uses single quotes (e.g., person['name']), the inner quotes can end the string early, causing invalid syntax. Switching the outer f-string to double quotes (while keeping inner single quotes) prevents the conflict.

How do f-strings handle zero-padding for integers?

By using a format specifier after a colon. For example, :02d pads an integer to width 2 with leading zeros. Increasing the width (e.g., :04d) yields four-digit zero-padded values, while numbers that already meet the width (like 10 for width 2) don’t get extra padding.

How can f-strings control the number of digits shown for floating-point values?

Use a precision specifier with :.4f (or another number). The transcript demonstrates printing pi with a fixed precision, which rounds the value rather than simply truncating it.

How can an f-string produce a nicely formatted date instead of a raw datetime string?

Use strftime-style directives inside the formatting. The example uses %B for the full month name, %d for the day, and %Y for a four-digit year, producing output like “January 1st, 1990” rather than the default datetime representation.

Review Questions

  1. When would you prefer an f-string over str.format(), and what readability issue does it solve?
  2. How do you avoid quote-related syntax errors when using dictionary lookups inside an f-string?
  3. What do the format specifiers :02d and :.4f control, and how would changing the numbers affect the output?

Key Points

  1. 1

    Use f-strings (Python 3.6+) to embed variables and expressions directly inside curly braces for clearer string construction.

  2. 2

    Replace placeholder-and-argument juggling from str.format() with direct in-place interpolation for better maintainability.

  3. 3

    Call methods like .upper() inside f-string braces to transform values inline.

  4. 4

    When accessing dictionary keys inside f-strings, avoid quote conflicts by using double quotes for the outer f-string if the lookup uses single quotes.

  5. 5

    Use format specifiers after a colon to control output: :0Nd for zero-padding integers and :.Nf for float precision.

  6. 6

    F-strings can evaluate expressions and calculations inside braces, enabling computed text without extra steps.

  7. 7

    For dates, apply strftime directives such as %B, %d, and %Y to generate human-friendly date strings.

Highlights

F-strings make interpolation more intuitive by placing values exactly where they appear in the output string.
Inline method calls (like .upper()) and expressions (like 4 * 11) can live inside the braces.
Quote handling matters for dictionary lookups: outer double quotes prevent inner single-quote syntax errors.
Format specifiers let f-strings do real formatting work—zero-padding integers and rounding floats to a chosen precision.
Date output can be made readable by using strftime codes (%B, %d, %Y) inside the f-string formatting.

Topics

  • F-Strings
  • String Formatting
  • Dictionary Interpolation
  • Numeric Precision
  • Date/Time Formatting

Mentioned