Multiline Python fstring statement

In Python, you can write a string on multiple lines to increase codebase readability:

python> message = (
    "This is one line, "
    "this one continues.\n"
    "This one is new."
)
python> message
'This is one line, this one continues.\nThis one is new.'
python> print(message)
This is one line, this one continues.
This one is new.

This is purely visual and relies on wrapping the split sliced string within a tuple.

This becomes particularly handy if you are using a Python code formatter (e.g. black, mypy and pylint usually come together). If so, you might have stumbled on the line-too-long error messages.

One more example

def greet(name: str) -> None:
    message = (
        f"Hello {name}, this line "
        f"and this one "
        f"will be displayed on the same line.\n"
        f"but not this one"
    )
    print(message)
python> greet("Olivier")
Hello Olivier, this line and this one will be displayed on the same line.
but not this one

Leave a Reply

Your email address will not be published. Required fields are marked *