Explain Codes LogoExplain Codes Logo

Multiline f-string in Python

python
f-strings
pep-8
readability
Nikita BarsukovbyNikita Barsukov·Feb 28, 2025
TLDR

Deploy a multiline f-string in Python using triple-double-quotes ("""), interspersing variables with {} for interpolation:

name, age, profession = "Alice", 30, "Developer" info = f"""Name: {name} Age: {age} Profession: {profession}""" print(info)

Produces:

Name: Alice
Age: 30
Profession: Developer

Ensure correct indentation within """ to maintain formatting in the output.

PEP-8 compliance for long line wrapping

When your f-string starts to stretch out like a Python itself, you might want to split it across multiple lines. Wrap these long lines with parentheses for style and comfort:

item, price, quantity = "Widget", 19.99, 10 receipt = ( # Behold! Our receipt carved from rock! f"Item: {item}\n" f"Price: ${price:.2f}\n" f"Quantity: {quantity}\n" f"Total: ${price * quantity:.2f}" ) print(receipt)

Our Pythonic friends at PEP-8 would appreciate this over the (often maligned, rarely admired) backslash (\). Avoids curious linter looks (e.g., E501 for line too long).

Define variables for readability and efficiency

Predefine your variables before pressing them into f-string service. It makes your code as readable as a children's book and as maintainable as an old car:

username = "J.Doe" user_age = 42 user_bio = "Enthusiastic Python developer" profile = ( f"Username: {username}\n" f"Age: {user_age} years old\n" f"Bio: {user_bio}" ) print(profile)

Code lean, profile mean: variables are evaluated once, not each time they're called upon.

Simple concatenation, minus the extras

By applying the parentheses trick to your f-string, you’ll gain the power to concatenate your strings as in:

user = "Jane" tasks = 5 task_msg = ( # Rolling three f-strings in one! f"User {user} has " f"{tasks} new tasks" # Python's version of "one does not simply..." f"{'s' if tasks > 1 else ''}." ) print(task_msg)

This method helps you avoid the dreaded .join() or the lost-looking comma while maintaining PEP-8's blessing and ticking all the boxes for format specifiers and interpolation.

Triple quotes for the win

When the parentheses feel too enclosing and preserve every bit of white space is crucial, drink a toast to triple quotes:

query = f"""SELECT * FROM users WHERE name = '{name}' AND age >= {age}"""

Perfect for SQL queries, documentation strings, or any case where preserving format is crucial.

Explicit readability: the true Python way

A perfectly crafted f-string spans lines with as much grace as a ballerina during Swan Lake:

title = "Multiline f-string guide" content = "How to craft beautiful Python strings" footer = "Happy coding!" message = ( # No duck typing, but f-lining! f"Title: {title}\n" f"Content:\n{content}\n" f"{footer}" )

Your f-string is now not just a code snippet — it's a readable, PEP-8 conforming, fully functional Pythonic masterpiece.