Multiline f-string in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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
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
A backslash (\) immediately after the opening """ suppresses the first newline. textwrap.dedent() removes common leading whitespace from indented multiline strings.
Parenthesized Implicit Concatenation
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
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
Format specifiers after : inside {} control alignment (<, >, ^), width, precision, and grouping (, for thousands separators).
Debugging with = (Python 3.8+)
Common Pitfalls
- Missing
fprefix on one part: In parenthesized concatenation, each string literal needs its ownfprefix.f"Hello " "world {name}"does not interpolatenamebecause the second string is a plain string. - Backslashes inside
{}(pre-3.12):f"path: {path.replace('\\', '/')}"raises aSyntaxErrorbefore 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. Usetextwrap.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
fprefix - 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
Related reading
- Multiple-output Gaussian Process regression in scikit-learn
- Multiple aggregations of the same column using pandas GroupBy.agg
- Multiple Host web app (Redirecting/Routing) in Django middleware / view
- Multiple Linear Regression with specific constraint on each coefficients on Python
- Multiple lines on same plot with incremental logging - wandb
- Multiple output regression or classifier with one or more parameters with Python
- Multiple sessions and graphs in Tensorflow in the same process
- multiple tasks using python asyncio
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.