Online Tutorials & Training Materials | STechies.com
Register Login

Python: Insert New Line into String

04 May 2020 1:55 pm || 0

While coding in Python, you might want your code to print out certain elements on the next line or a new line. Or you might just want to execute a statement and want the cursor to move to the next line.

The newline characters are used in these situations. You can add a newline character between strings too.

We will focus on the newline character in Python and its use in this article.

Python: Insert New Line into String

What is "\n" in Python?

In Python, you can specify the newline character by "\n". The "\" is called the escape character used for mentioning whitespace characters such as \t, \n and \r. Mentioning the newline character using \n will bring the cursor to the consecutive line.

Example 1

print('Hello \n STechies')

Output:

Hello
STechies

We can see in the example above that the newline character has moved the cursor to the next line. Hence, the string “STechies” is printed on the next line.

Example 2:

# Python program to insert new line in string

# Declare a List
mystring = "Hello\n\
This is\n\
Stechies\n\
for,\n\
Tech tutorials."

# Print string
print(mystring)

Output:

Hello
This is
Stechies
for,
Tech tutorials.

Just like the previous example, the newline character mentioned after every line of code brings that string to the next line. This is observed from the final output.

Using "multi-line" Strings

# Python program to insert new line in string

# Declare a List
mystring = """Hello
This is
Stechies
for,
Tech tutorials."""

# Print string
print(mystring)

Output:

Hello
This is
Stechies
for,
Tech tutorials.

Explanation

Another way to insert a new line between strings in Python is by using multi-line strings. These strings are denoted using triple quotes (""") or ('''). These type of strings can span across two or three lines. We can see in the output that the strings are printed in three consecutive lines as specified in the code with the help of triple quotes.

Platform Independent Line Breaker: Linux, Windows & Others

# Import os Module
import os

mysite = 'STechies'+ os.linesep + 'Smart Techies'
# Print mystring
print(mysite)

Output:

STechies
Smart Techies

Explanation

There is yet another way to insert a new line – by using a platform-independent line breaker. This is achieved by using the newline character in Python’s os package called linesep. The os.linesep is used for separating lines on that particular platform such as Windows or Linux.

But it is recommended that you do not use linesep for files opened in the text mode. You can just use \n for specifying a newline character, and Python will translate it to the appropriate newline character for that platform.

Conclusion

Newline characters are important for your code output to look neat and clean. But make sure to use the escape characters to specify the newline properly.