Skip to content

Python new line in string

  • by

Use character \n in Python string to get a new line in the string. You can add a newline character between strings too. The “\” is called the escape character used for mentioning whitespace characters such as \t, \n, and \r.

print('First line \n Second line') 

Mentioning the newline character using \n will bring the cursor to the consecutive line.

Python new line in the string

Simple example code.

print('First line \n Second line')

# Declare a List
mystring = "Hello\n\
This is\n\
Python\n\
code,\n\
tutorials."

# Print string
print(mystring)

Output:

Python new line in string

Using “multi-line” Strings

This is 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 types of strings can span across two or three lines.

mystring = """Hello
This is
Code
for,
Python."""

# Print string
print(mystring)

How do I specify new lines in a string in order to write multiple lines to a file?

Answer: Just use \n; Python automatically translates that to the proper newline character for your platform.

print('First line \n Second line') 

where \n is the newline character?

This would yield the result:

First line
 Second line

If you use Python 2, you do not use the parentheses on the print function.

Do comment if you have any doubts or suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading