Python new line in variable

How to Fix SyntaxError: f-string expression part cannot include a backslash

Photo by Kevin Mak on Unsplash

Introduction

In Python, it’s impossible to include backslashes in curly braces {} of f-strings. Doing so will result into a SyntaxError:

>>> f'{\}'
SyntaxError: f-string expression part cannot include a backslash

This behaviour aligns perfectly with PEP-0498 which is about Literal String Interpolation:

Backslashes may not appear inside the expression portions of f-strings, so you cannot use them, for example, to escape quotes inside f-strings

In the following sections we will explore a couple of options you can use in order to add backslashes (including new lines) in f-strings.

Using backslashes in f-strings

As we already discussed, backslashes cannot be used directly in Python f-strings. However, there is an easy workaround that allows us to include backslashes in order to denote for example new lines, tabs etc.

Let’s suppose that we have a list of integers we want to print out to the standard output.

nums = [10, 20, 30] 
print(f"Numbers:\n {'\n'.join(map(str, nums))}")

As expected, the above will fail with

SyntaxError: f-string expression part cannot include a backslash

One workaround is to add the new line character (i.e. '\n') into a string variable and then reference that variable when printing out the numbers. For example,

new_line = '\n'
nums = [10, 20, 30]
print(f"Numbers:{new_line}{new_line.join(map(str, nums))}")

And the output should be

Numbers:
10
20
30

Note that you can do this for pretty much every character that requires a backslash. For instance, let’s suppose you want to use a tab in an f-string. The following should to the trick:

tab = '\t'
print(f'Hello {tab} World!')
# Output
Hello World!

How to add new line in f-strings

For new lines in particular, there is also another approach that we can follow in order to add new line characters in Python f-strings.

The os package comes with some functionality about Miscellaneous System Information. This includes os.linesep that returns the new line character.

The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows.

For example,

import osnums = [10, 20, 30] 
print(f"Numbers:{os.linesep}{os.linesep.join(map(str, nums))}")

And the output will again be

Numbers:
10
20
30

Note that you must avoid using os.linesep as a line terminator when writing files opened in text mode. Instead, you have to use use a single '\n'.

Another possibility, is to use chr() function to generate a new line character. The chr() function in Python returns a string representation of the input integer that corresponds to a Unicode character. The decimal value of 10 in Unicode is equivalent to the line feed (i.e. new line).

>>> chr(10)
'\n'

Therefore, in order to add new lines in f-strings using chr() all you need to do is

nums = [10, 20, 30] 
print(f"Numbers:{chr(10)}{chr(10).join(map(str, nums))}")
# Numbers:
# 10
# 20
# 30

Final Thoughts

In today’s article we discussed one limitation of Python that stops us from using backslashes in f-strings. We introduced a few possible workarounds and we also explored in particular how to implicitly add new lines in Python f-strings.

Essentially, you have three options; The first is to define a new line as a string variable and reference that variable in f-string curly braces. The second workaround is to use os.linesep that returns the new line character and the final approach is to use chr(10) that corresponds to the Unicode new line character.

Hey folks! Hope you all are doing well. In this article, we will be unveiling Different ways to add a newline character in Python(\n) to the output of the data to be printed.

So, let us get started!


Technique 1: Add a newline character in a multiline string

Python Multiline String provides an efficient way to represent multiple strings in an aligned manner. A newline(\n) character can be added to multiline string as shown below–

Syntax:

string = '''str1\nstr2....\nstrN'''

We can easily use ‘\n’ before every string which we want to display on a new line in a multiline string.

Example:

str='''Hello all!! \nI am Pythoner \nWelcome to the AskPython Tutorial''' 
print(str)

Output:

Hello all!! 
I am Pythoner 
Welcome to the AskPython Tutorial


Technique 2: Addition of newline to a Python List

Python List can be considered as a dynamic array that stores heterogeneous elements into it at dynamic runtime.

The string.join() function can be used to add a newline amidst the elements of the list as shown below–

Syntax:

Example:

lst = ['Python','Java','Kotlin','Cpp']
print("List before adding newline character to it:",lst)
lst = '\n'.join(lst)
print("List after adding newline character to it:\n",lst)

Output:

List before adding newline character to it: ['Python', 'Java', 'Kotlin', 'Cpp']
List after adding newline character to it:
 Python
Java
Kotlin
Cpp


Technique 3: Displaying a newline on the console

At the very beginning stage, it is important to know the execution of functions on the console. To add a newline on the console use the below code–

Example:

Python new line in variable
Python newline with console


Technique 4: Displaying a new line through print statement

The newline character can be added to print() function in order to display the string on a new line as shown below–

Syntax:

print("str1\nstr2\n...\strN")

Example:

print("Hello Folks! Let us start learning.")
print("Statement after adding newline through print() function....")
print("Hello Folks!\nLet us start learning.")

Output:

Hello Folks! Let us start learning.
Statement after adding newline through print() function....
Hello Folks!
Let us start learning.


Technique 5: Add a newline character through Python f-string

Python f-string also represents the string statements in a formatted manner on the console. To add a newline character through a f-string, follow the below syntax:

newline = '\n'
string = f"str1{newline}str2"

Example:

newline = '\n'
str = f"Python{newline}Java{newline}Cpp"
print(str)

Output:


Technique 6: Writing a new line to a file

A newline character can be appended to a Python file using the below syntax:

Syntax:

Example:

Here, we have used Python.txt file with the below predefined content as shown–

Python new line in variable
Python Text-file

import os 
file = "/Python.txt" 
with open(file, 'a') as file: 
  file.write("\n")  

Output:

As seen below, a new line gets added to the file content.

Python new line in variable
Add newline To A Python File


Conclusion

By this, we have come to the end of this topic. Feel free to comment below incase you come across any question.

Till then, Happy Learning!!


References

  • Adding newline to a Python file — Quora

How do you add a new line to a variable in Python?

Newline character in Python: In Python, the new line character “\n” is used to create a new line.

How do you print a new line after a variable in Python?

Use the addition operator to print a new line after a variable, e.g. print(variable + '\n') . The newline ( \n ) character is a special character in python and is used to insert new lines in a string.

What is \N in Python string?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

Can you break a line in Python?

Python supports implicit line continuation. This means you can break long lines of code. As a matter of fact, you should limit all lines of code to a maximum of 79 characters.