7 Best Ways to Use Newline in an F-String

Problem Formulation

In the following example, you use a newline character '\n' inside the curly braces of an f-string:

my_list = ['Alice', 'Ann', 'Adam']
my_string = f'Names:\n{"\n".join(my_list)}'
print(my_string)

But if you run this code, Python raises a SyntaxError: f-string expression part cannot include a backslash. ⚑

The reason is that there is a limitation in versions of Python before 3.12 where backslashes are not allowed inside the expression portions of f-strings.

πŸ’‘ Background Info: In Python 3.6 and later, f-strings offer a convenient way to format output with great flexibility. They allow you to easily incorporate variables and expressions within string literals. To create a formatted string, you can simply use an “f” or “F” prefix before the opening quotes of the string and enclose identifiers like variables in curly braces ({}).

There are multiple ways to resolve this issue.

Method 1: Using an Intermediate Variable

You can create an intermediate variable that holds the string with newlines and then use this variable inside the f-string.

my_list = ['Alice', 'Ann', 'Adam']
new_line_str = "\n".join(my_list)
my_string = f'Names:\n{new_line_str}'
print(my_string)

Method 2: Using chr()

The chr() function in Python returns a string representing a character whose Unicode code point is the integer passed to the function. For example, chr(10) returns a newline character ('\n'). You can use the function inside the formatting specifier {...}.

my_list = ['Alice', 'Ann', 'Adam']
my_string = f'Names:\n{chr(10).join(my_list)}'
print(my_string)

Output:

Names:
Alice
Ann
Adam

Method 3: Using Concatenation

Concatenate the f-string with a string that contains the newline characters.

my_list = ['Alice', 'Ann', 'Adam']
my_string = 'Names:\n' + "\n".join(my_list)
print(my_string)

Method 4: Using a Function

Define a function that returns the desired string and call it inside the f-string.

my_list = ['Alice', 'Ann', 'Adam']

def get_names_string(names_list):
    return "\n".join(names_list)

my_string = f'Names:\n{get_names_string(my_list)}'
print(my_string)

Method 5: Using a Placeholder

Use a placeholder in the f-string and replace it with a newline character afterward. Make sure your string doesn’t already contain the placeholder or you’d mess things up.

my_list = ['Alice', 'Ann', 'Adam']
my_string = f'Names:|x|{"|x|".join(my_list)}'.replace("|x|", "\n")
print(my_string)

Method 6: Using eval() Function (Not Recommended)

Although it’s possible to use eval() to evaluate a string as a Python expression, it’s generally not recommended due to security risks.

my_list = ['Alice', 'Ann', 'Adam']
s = "'\\n'.join(my_list)"
my_string = f'Names:\n{eval(s)}'
print(my_string)

The provided Python code snippet demonstrates a method to concatenate and display a list of names, each on a new line, using f-strings and the eval() function.

Initially, a list my_list is defined, containing three string elements: 'Alice', 'Ann', and 'Adam'. Subsequently, a string s is crafted, embedding a Python code expression as a string, specifically: "'\n'.join(my_list)", where "\n" represents a newline character when evaluated.

The eval() function is utilized within an f-string to evaluate s as a Python expression, effectively executing the .join() method on my_list with a newline character as the separator.

The resulting string, which concatenates "Names:\n" with the joined names, each on a new line, is stored in my_string and printed to the console, yielding an output that lists the names under the label "Names:".

Method 7: Update Your Python Version to 3.12!

I should have made this Method 1. In Python 3.12 and later, you can use backslashes inside the expression portions of f-strings, so the original example would work as expected.

βš‘πŸ§‘β€πŸ’» Recommended: How to Update Python?