Skip to content

\n in Python - Adding a New Line

The \n in Python is the newline character. It is used to split strings onto separate lines. The data after the \n character will be placed on a new line.

Take the following example of a string printed on a single line:

string = "Classical Finance"

print(string)

>> Classical Finance

However, if we want to put the output on separate lines we would use \n.

string = "Classical \nFinance"

print(string)

>> Classical 
>> Finance

This guide is going to explain how the new line character works. First, we are going to understand what strings are. Then we are going to look into Python escape characters.

After exploring the \n, we will mention alternatives that serve the same purpose.

What does \n do in Python?

We now know that it creates a new line but let's look at some python concepts to cement our understanding.

Understanding strings

Python has several data types. They include:

  • strings
  • integers
  • floats
  • complex
  • boolean
  • lists
  • tuples
  • range

You can study the rest at your leisure. Strings are our current concern for the purposes of this guide.

Python strings are Unicode character sequences. Any combination of alphabetical characters and digits that can be interpreted by a human being are more often than not strings.

This entire guide is probably being displayed on your screen with the help of a print function as a string.

Strings are enclosed inside double quotes or single quotes. Like with most data types, a print function is used to output strings to users. Here are some  examples of strings:

‘My name is Andre. I am a Python programmer.’
‘I am learning Python! You are learning Python! He is learning Python! She is learning Python! They are learning Python. But not everyone is learning Python, why?’
“Christmas is nearly upon us. I hope I will not be haunted by the ghost of Christmas 2020.”
“I am a human. At least I have been led to believe I am one. Who knows?”
‘Hello’
‘n’

Notice how all the examples above are displayed on the same line? It is crucial to keep this fact in mind as we proceed.

Escape characters

Python uses various characters and symbols for purposes we might not use them in ordinary writing. To make matters more confusing, certain symbols mean more than one thing depending on the context. As a result, Python needs a way of knowing the right context.

The same principle is found in spoken languages. “Hear” and “here” do not mean the same thing, although they sound similar. “Spring” can mean jumping, a place where you get water, or a weather season. Let us not forget slang and metaphors, where things like “she is loaded” do not mean what they appear to mean.

As an English speaker, you look at the words before and after the homonym to determine the context. Similarly, Python needs a way of knowing the context under which a character is being used.

Here are a couple of examples:

The same symbol is used for an apostrophe and a single quote. (‘Andre’) and (Andre’s).

Double quotes inside another pair of double quotes look like you are trying to nest strings. (“I am a human, scientifically also known as “homo sapiens sapiens””)

The above code snippets are why we need a way of making Python understand the correct context under which we are using certain symbols. This process is known as escape characters.

Understanding backslash in Python

The backslash (\) tells Python what follows is an escape character. It tells Python to interpret that character under a different context than it usually does.

Here is an example:

x = ‘That is Arya’s sword’ 
#This produces a syntax error. As far as Python is concerned, you opened another set of single quotes without closing them.

The correct way to write the above code is as follows:

x = ‘That is Arya\’s sword.’

What is backslash n Python?

The backslash is a powerful character in Python. It does not only tell Python the character following it should be treated differently. It can also tell the program the next character has special functionalities.

Did you notice how every single string we have dealt with so far in this guide only has one line? What if we want a string with multiple lines? For example, this guide which has well over 50 lines?

We can use backslash n (\n) to tell Python everything after \n comes on a new line. Using the backslash changes “n” from a normal alphabetical character, and turns it into what we call a new line character.

Here is an example of how this is done:

x = "Good morning. \n My name is David, I love to climb trees. \n What is your name? \n Okay, see you tomorrow! "
print (x)

The result will be as follows:

Good morning.
My name is David, I love to climb trees.
What is your name?
Okay, see you tomorrow!

The above output is split over multiple lines. It is also easier on the eye than the original wall of text.

Using triple quotes instead of \n

The \n pairing is not the only way to display your strings across lines. You can also use triple quotation marks.

Every time you press enter or create a new line in your text editor / ide, Python accepts it as a new line as long as it is between triple quotes. Similarly, these line breaks will be displayed when you print your code.

Here is an example:

x = """
Arya of house Stark.
Tommen of house Baratheon.
Cersei of house Lannister.
The red viper of Dorne.
Brianne of Tarth.
"""
print (x)

The result will be as follows:

Arya of house Stark.
Tommen of house Baratheon.
Cersei of house Lannister.
The red viper of Dorne.
Brianne of Tarth.

Use case

You might be wondering if you will ever need to use either \n or triple quotes.

Multiple lines might not be necessary if your code only displays a few details. But the more information you want to display, the more lines you need. This is because reading line by line is easier than trying to figure out a wall of text.

Note the following example:

Jon Snow Arya Brianne Sansa Cersei Lannister Tyrion Daenerys Edmure Barristan Selmy

If you are not familiar with these characters, would you be able to tell who is who? Are all of the above first names or are they name and surname pairs? Is there someone called Tyrion Daenerys, or are they two separate people?

Things would make more sense if the output looked something like this:

Jon Snow
Arya
Brianne
Sansa
Cersei Lannister
Tyrion
Daenerys
Edmure
Barristan Selmy

Because each person is on a single line, it is easier to identify who has the last name, and whose has been omitted.

Here is a real-life example to think about. This guide is about 1200 words long. Would you read the entire thing if it was one giant paragraph of text? You might try to, but it would not be easy on your eyes.

Should I use the new line character or triple quotes

Whether you should use \n or triple quotes is a stylistic choice. It will depend on a few factors.

Firstly, what do you prefer? Different programmers prefer to do things a certain way. As long as you are consistent and your code is readable, either method is fine.

Second, does your programming style guide recommend \n or triple quotes? Always follow the relevant style guide when working in teams or on open source projects.

Other characters

There are many other escape characters in Python aside from the new line character. Here are some of them for your own interest:

  • \\ (backslash)
  • \r (carriage Return)
  • \t (tab)
  • \b (backspace)
  • \f (form feed)

Conclusion

There are many reasons to split your string into multiple lines. The more popular ones are displaying readable text and making it easier for users to read/comprehend a print statement.

Triple quotes and \n are two ways of splitting your output into multiple lines. Which of the two you will use will depend on your preference or your team and project’s style guide.

Comments

Latest