Python
f-string
multiline strings
programming
Python 3.6+

Multiline f-string in Python

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python f-strings (formatted string literals, Python 3.6+) support multiline content through two approaches: triple-quoted f-strings (f"""...""") for strings that should contain actual newlines, and implicit string concatenation with parentheses for long expressions that should be a single line. Triple-quoted f-strings preserve newlines and indentation, while parenthesized f-strings let you break long formatting expressions across multiple source lines without adding newlines to the output.

Triple-Quoted f-strings

python
1name = "Alice"
2age = 30
3city = "Portland"
4
5message = f"""
6Name: {name}
7Age: {age}
8City: {city}
9"""
10print(message)
11# (blank line)
12# Name: Alice
13# Age: 30
14# City: Portland
15# (blank line)

Triple-quoted f-strings (f"""...""" or f'''...''') preserve all whitespace and newlines between the quotes. The output includes the actual newline characters in the string.

Removing Leading/Trailing Whitespace

python
1from textwrap import dedent
2
3# Strip the leading newline and trailing whitespace
4message = f"""\
5Name: {name}
6Age: {age}
7City: {city}"""
8print(message)
9# Name: Alice
10# Age: 30
11# City: Portland
12
13# Using textwrap.dedent for indented blocks
14def get_report(user):
15    return dedent(f"""\
16        User Report
17        -----------
18        Name: {user['name']}
19        Role: {user['role']}
20    """).strip()
21
22print(get_report({"name": "Alice", "role": "Admin"}))
23# User Report
24# -----------
25# Name: Alice
26# Role: Admin

A backslash (\) immediately after the opening """ suppresses the first newline. textwrap.dedent() removes common leading whitespace from indented multiline strings.

Parenthesized Implicit Concatenation

python
1name = "Alice"
2score = 95.678
3status = "active"
4
5# Multiple f-strings joined into one line (no newlines in output)
6message = (
7    f"User: {name}, "
8    f"Score: {score:.1f}, "
9    f"Status: {status.upper()}"
10)
11print(message)
12# User: Alice, Score: 95.7, Status: ACTIVE

Python automatically concatenates adjacent string literals. Wrapping in parentheses lets you split a long f-string across multiple source lines without introducing newlines in the output. Each piece must have its own f prefix.

Expressions in Multiline f-strings

python
1items = ["apple", "banana", "cherry"]
2prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00}
3
4# Expressions and method calls inside {}
5summary = f"""
6Shopping List ({len(items)} items):
7{chr(10).join(f'  - {item}: ${prices[item]:.2f}' for item in items)}
8Total: ${sum(prices[i] for i in items):.2f}
9"""
10print(summary)
11# Shopping List (3 items):
12#   - apple: $1.20
13#   - banana: $0.50
14#   - cherry: $2.00
15# Total: $3.70
16
17# Note: backslashes are NOT allowed inside {} in f-strings (before Python 3.12)
18# Use chr(10) for newline or a variable
19newline = "\n"
20names = f"Names:{newline}{newline.join(['Alice', 'Bob', 'Charlie'])}"

You can embed any valid Python expression inside {}, including comprehensions, function calls, and ternary operators. Before Python 3.12, backslashes (\n, \t) are not allowed inside the {} expression — use chr(10) or assign to a variable.

Format Specifiers

python
1value = 1234567.891
2
3# Number formatting in multiline f-strings
4report = f"""
5Financial Report
6================
7Revenue:  {value:>15,.2f}
8Expenses: {value * 0.7:>15,.2f}
9Profit:   {value * 0.3:>15,.2f}
10"""
11print(report)
12# Financial Report
13# ================
14# Revenue:   1,234,567.89
15# Expenses:    864,197.52
16# Profit:      370,370.37
17
18# Alignment and padding
19headers = f"""
20{'Name':<20} {'Score':>10} {'Grade':^10}
21{'─' * 20} {'─' * 10} {'─' * 10}
22{'Alice':<20} {95:>10.1f} {'A':^10}
23{'Bob':<20} {82:>10.1f} {'B':^10}
24"""
25print(headers)

Format specifiers after : inside {} control alignment (<, >, ^), width, precision, and grouping (, for thousands separators).

Debugging with = (Python 3.8+)

python
1x = 42
2y = [1, 2, 3]
3
4# The = suffix prints "expression=value"
5debug = f"""
6Debug Info:
7  {x = }
8  {len(y) = }
9  {y[0] + y[1] = }
10"""
11print(debug)
12# Debug Info:
13#   x = 42
14#   len(y) = 3
15#   y[0] + y[1] = 3

Common Pitfalls

  • Missing f prefix on one part: In parenthesized concatenation, each string literal needs its own f prefix. f"Hello " "world {name}" does not interpolate name because the second string is a plain string.
  • Backslashes inside {} (pre-3.12): f"path: {path.replace('\\', '/')}" raises a SyntaxError before Python 3.12. Assign the expression to a variable first or use a helper function.
  • Unintended indentation in triple-quoted strings: Indenting the content of f"""...""" inside a function adds literal spaces to the output. Use textwrap.dedent() to strip common leading whitespace.
  • Curly braces in output: To include literal { or } in an f-string, double them: f"{{value}}" outputs {value}. A single { is interpreted as the start of an expression.
  • Performance with complex expressions: Embedding complex comprehensions or function calls in {} hurts readability. Extract complex logic into variables before the f-string for clarity.

Summary

  • f"""...""" — triple-quoted f-string for multiline output with actual newlines
  • (f"..." f"..." f"...") — parenthesized concatenation for long single-line strings split across source lines
  • Each string literal in concatenation needs its own f prefix
  • Use textwrap.dedent() to handle indentation in triple-quoted f-strings
  • Use chr(10) or a variable for newlines inside {} before Python 3.12
  • Format specifiers (:>10,.2f) work the same in multiline f-strings as single-line

Course illustration
Course illustration

All Rights Reserved.