Skip to content

Python multiline f string | Example code

  • by

The preferred way to print multiline f string is by using Python’s implied line continuation inside parentheses, brackets, and braces.

The following would solve your problem in a PEP-8 compliant way.

return (
    f'{self.date} - {self.time}\n'
    f'Tags: {self.tags}\n'
    f'Text: {self.text}'
)

Note: Python strings will automatically concatenate when not separated by a comma, so you do not need to explicitly call join().

Example multiline f string Python

Simple example code multiline f-string in Python

Example 1

If you want to format standard but want the more appealing look

date = "01/31/2021"
time = "9:30 AM"
tags = ["high value", "high cost"]
text = "Hello"


def get():
    return (
        f'{date} - {time}\n'
        f'Tags: {tags}\n'
        f'Text: {text}'
    )


print(get())

Output:

Python multiline f string

Example 2

If you want to have it formatted exactly as input.

date = "01/31/2021"
time = "9:30 AM"
tags = ["high value", "high cost"]
text = "Hello"


def get():
    return f'''{date} - {time},
    Tags: {tags},
    Text: {text}
    '''


print(get())

Output:

multiline f string python

Example 3

Python f string code.

name = "John"
age = 18
print(f"Hello, {name}. You are {age}.")

Output:

Hello, John. You are 18.

Do comment if you have any doubts and suggestions on this Python f string tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading