How to create multiline f-strings?

Creating Multiline F-Strings in Python

In Python, f-strings (formatted string literals) provide a concise and efficient way to embed expressions within string literals. By default, f-strings are single-line, but you can create multiline f-strings using a combination of string literals and the f prefix.

Multiline F-Strings Using Triple Quotes

One way to create multiline f-strings is by using triple quotes (either single or double quotes). This allows you to create strings that span multiple lines, and you can still embed expressions within them using the f prefix.

Here's an example:

name = "Alice"
age = 25
message = f"""
Hello, my name is {name} and I am {age} years old.
I am a Python enthusiast and I love learning new things.
"""
print(message)

Output:

Hello, my name is Alice and I am 25 years old.
I am a Python enthusiast and I love learning new things.

In this example, the multiline f-string is created using triple double quotes (""""), and it includes two expressions ({name} and {age}) that are replaced with the corresponding values.

Multiline F-Strings Using Newline Characters

Alternatively, you can create multiline f-strings by using newline characters (\n) within a single-line f-string. This can be useful if you don't need to span multiple paragraphs, but still want to create a multiline string.

name = "Bob"
age = 30
message = f"Hello, my name is {name} and I am {age} years old.\nI enjoy coding in Python."
print(message)

Output:

Hello, my name is Bob and I am 30 years old.
I enjoy coding in Python.

In this example, the newline character (\n) is used to split the f-string into two lines.

Multiline F-Strings and Indentation

When using multiline f-strings, it's important to consider the indentation of the code. The indentation within the f-string will be preserved, so you may need to adjust the indentation of your code to ensure the f-string is formatted correctly.

Here's an example:

name = "Charlie"
age = 35
message = f"""
    Hello, my name is {name} and I am {age} years old.
    I am learning to create multiline f-strings in Python.
"""
print(message)

Output:

    Hello, my name is Charlie and I am 35 years old.
    I am learning to create multiline f-strings in Python.

In this example, the multiline f-string is indented with four spaces, and the output preserves this indentation.

By using multiline f-strings, you can create more readable and expressive string literals in your Python code, making it easier to work with complex or lengthy text.

0 Comments

no data
Be the first to share your comment!