In this short tutorial, we look at how to add a Python new line. We look at the Python new line character and how the other methods can be used.
Table of Contents - Python new line:
- Python new line
- Newline character in Python
- Multi-line string
- Closing thoughts - Python new line
Python new line:
In programming, it is a common practice to break lines and display content in a new line. This improves the readability of the output. Apart from that, you would frequently come across the new line character a lot while working with files.
Hence it is quite important that you understand how to add a new line and familiarise yourself with how the new line character works. This tutorial is aimed to do the same.
Newline character in Python:
In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.
Code and Explanation:
str_1 = "Hire the top \n1% freelance developers"
print[str_1]
‘’’Output - Hire the top
1% freelance developers’’’
As aforementioned,
the character after the new line character is printed in a new line.
Different ways to implement this would include either adding it to string directly, or concatenating it before printing it. A common question that beginners have while learning how to apply a new line is - since we are adding it to a string - Why doesn’t Python print “\n” as it is? And how does it know that a new line must be added?
Well, the backslash [“\”] in the new line character is called an escape sequence. Escape sequences are used to add anything illegal to a string. This way Python understands that the following character is not a part of a string and executes it.
Multiline Strings:
Multiline strings are another easy way to print text in a new line. As the name suggests the string itself spans over multiple lines. These strings can be assigned by using either 3 double quotes or 3 single quotes. Python understands that the string is a multiline string and prints it as such.
Code and Explanation:
str_1 = """Hire the top
1% freelance
developers"""
print[str_1]
'''Output - Hire the top
1% freelance
developers'''
In the above example, the string is printed in the same way as the information was passed.
Closing thoughts - Python new line:
Although both methods can be used in Python to add new lines I would recommend using the first method as it is the most commonly accepted method. Also, given Python has an in-built character that facilitates this it is best to utilize it.
However, please feel free to explore and understand how the multiline method works.
There are two functions that give an object's string representation, repr[]
and str[]
. The former is designed to convert the object to as-code string, while the latter gives user-friendly string.
When you input the variable name in the command line, repr[]
is used, and \n
character is shown as \n
[as-code]. When you use print
, str[]
is used, and \n
is shown as a new line [user-friendly].
By the way, str
is a bad name for
a variable, as it's the same as the built-in.
How can I indicate a newline in a string in Python, so that I can write multiple lines to a text file?
asked Jul 16, 2012 at 2:14
FabianCookFabianCook
19.9k16 gold badges65 silver badges112 bronze badges
2
It depends on how correct you want to be. \n
will usually do the job. If you really want to get it right, you look up the newline character in the os
package. [It's actually called linesep
.]
Note: when writing to files using the Python API, do not use the os.linesep
. Just use \n
; Python automatically translates that to the proper newline character for your platform.
Mateen Ulhaq
22.2k16 gold badges86 silver badges127 bronze badges
answered Jul 16, 2012 at 2:16
Charlie MartinCharlie Martin
108k23 gold badges192 silver badges258 bronze badges
3
The new line character is \n
. It is used inside a string.
Example:
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.
answered Sep 26, 2013 at 15:42
python_poweredpython_powered
1,1291 gold badge7 silver badges3 bronze badges
0
You can either write in the new lines separately or within a single string, which is easier.
Example 1
Input
line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"
You can write the '\n' separately:
file.write[line1]
file.write["\n"]
file.write[line2]
file.write["\n"]
file.write[line3]
file.write["\n"]
Output
hello how are you
I am testing the new line escape sequence
this seems to work
Example 2
Input
As others have pointed out in the previous answers, place the \n at the relevant points in your string:
line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"
file.write[line]
Output
hello how are you
I am testing the new line escape sequence
this seems to work
answered Jan 4, 2015 at 11:13
0
Platform-independent line breaker: Linux, Windows, and iOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print[keyword]
Output:
physical
distancing
answered Oct 26, 2019 at 18:55
0
Here is a more readable solution that will work correctly even if you aren't at top level indentation [e.g., in a function definition].
import textwrap
file.write[textwrap.dedent["""
Life's but a walking shadow, a poor player
That struts and frets his hour upon the stage
And then is heard no more: it is a tale
Told by an idiot, full of sound and fury,
Signifying nothing.
"""]]
answered Feb 10, 2015 at 16:31
fredcallawayfredcallaway
1,32211 silver badges7 bronze badges
0
Simplest solution
If you only call print
without any arguments, it will output a blank line.
print
You can pipe the output to a file like this [considering your example]:
f = open['out.txt', 'w']
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close[]
Not only is it OS-agnostic [without even having to use the os
package], it's also more readable than putting \n
within strings.
Explanation
The print[]
function has an optional keyword argument for the end of the string, called end
, which defaults to the OS's newline character, for eg. \n
. So, when you're
calling print['hello']
, Python is actually printing 'hello' + '\n'
. Which means that when you're calling just print
without any arguments, it's actually printing '' + '\n'
, which results in a newline.
Alternative
Use multi-line strings.
s = """First line
Second line
Third line"""
f = open['out.txt', 'w']
print s >> f
f.close[]
answered Jan 4, 2017 at 12:37
aalaapaalaap
3,9675 gold badges49 silver badges57 bronze badges
0
In Python you can just use the new-line character, i.e. \n
answered Jul 16, 2012 at 2:15
mhawkemhawke
81.6k9 gold badges113 silver badges135 bronze badges
0
As mentioned in other answers: "The new line character is \n. It is used inside a string".
I found the most simple and readable way is to use the "format" function, using nl as the name for a new line, and break the string you want to print to the exact format you going to print it:
Python 2:
print["line1{nl}"
"line2{nl}"
"line3".format[nl="\n"]]
Python 3:
nl = "\n"
print[f"line1{nl}"
f"line2{nl}"
f"line3"]
That will output:
line1
line2
line3
This way it performs the task, and also gives high readability of the code :]
answered Nov 28, 2019 at 13:43
Rea HaasRea Haas
1,43813 silver badges12 bronze badges
The same way with '\n'
, though you'd probably not need the '\r'
. Is there a reason you have it in your Java version? If you do need/want it, you can use it in the same way in Python too.
answered Jul 16, 2012 at 2:15
LevonLevon
132k33 gold badges197 silver badges186 bronze badges
0
It is worth noting that when you inspect a string using the interactive Python shell or a
Jupyter Notebook, the \n
and other backslashed strings like \t
are rendered literally:
>>> gotcha = 'Here is some random message...'
>>> gotcha += '\nAdditional content:\n\t{}'.format['Yet even more great stuff!']
>>> gotcha
'Here is some random message...\nAdditional content:\n\tYet even more great stuff!'
The newlines, tabs, and other special non-printed characters are rendered as whitespace only when printed, or written to a file:
>>> print['{}'.format[gotcha]]
Here is some random message...
Additional content:
Yet even more great stuff!
answered Jun 16, 2020 at 0:06
TrutaneTrutane
1,19011 silver badges11 bronze badges
Most escape characters in string literals from Java are also valid in Python, such as "\r" and "\n".
answered Jul 16, 2012 at 2:17
dolaamengdolaameng
1,3872 gold badges16 silver badges23 bronze badges
0
\n - simple newline character insertion works:
# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."
Output:
In [37]: print[test_line]
Hi!!!
testing first line..
testing second line..
and third line.....
answered Dec 18, 2017 at 21:46
SuryaSurya
10.1k4 gold badges54 silver badges37 bronze badges
In Python 3, the language takes care of encoding newlines for you in the platform's native representation. That means \r\n
on Windows, and just \n
on grown-up systems.
Even
on U*x systems, reading a file with Windows line endings in text mode returns correct results for text, i.e. any \r
characters before the \n
characters are silently dropped.
If you need total control over the bytes in the file, you can use binary mode. Then every byte corresponds exactly to one byte, and Python performs no translation.
>>> # Write a file with different line endings, using binary mode for full control
>>> with open['/tmp/demo.txt', 'wb'] as wf:
... wf.write[b'DOS line\r\n']
... wf.write[b'U*x line\n']
... wf.write[b'no line']
10
9
7
>>> # Read the file as text
>>> with open['/tmp/demo.txt', 'r'] as text:
... for line in text:
... print[line, end='']
DOS line
U*x line
no line
>>> # Or more demonstrably
>>> with open['/tmp/demo.txt', 'r'] as text:
... for line in text:
... print[repr[line]]
'DOS line\n'
'U*x line\n'
'no line'
>>> # Back to bytes!
>>> with open['/tmp/demo.txt', 'rb'] as binary:
... for line in binary:
... print[line]
b'DOS line\r\n'
b'U*x line\n'
b'no line'
>>> # Open in binary, but convert back to text
>>> with open['/tmp/demo.txt', 'rb'] as binary:
... for line in binary:
... print[line.decode['utf-8'], end='']
DOS line
U*x line
no line
>>> # Or again in more detail, with repr[]
>>> with open['/tmp/demo.txt', 'rb'] as binary:
... for line in binary:
... print[repr[line.decode['utf-8']]]
'DOS line\r\n'
'U*x line\n'
'no line'
answered Mar 23, 2021 at 5:45
tripleeetripleee
164k27 gold badges244 silver badges296 bronze badges
Use:
"{}\n{}\n{}".format[
"line1",
"line2",
"line3"
]
I personally prefer this format.
answered Nov 16, 2021 at 17:36
LynneLynne
3885 silver badges14 bronze badges
\n separates the lines of a string. In the following example, I keep writing the records in a loop. Each record is separated by \n
.
f = open["jsonFile.txt", "w"]
for row_index in range[2, sheet.nrows]:
mydict1 = {
"PowerMeterId" : row_index + 1,
"Service": "Electricity",
"Building": "JTC FoodHub",
"Floor": str[Floor],
"Location": Location,
"ReportType": "Electricity",
"System": System,
"SubSystem": "",
"Incomer": "",
"Category": "",
"DisplayName": DisplayName,
"Description": Description,
"Tag": tag,
"IsActive": 1,
"DataProviderType": int[0],
"DataTable": ""
}
mydict1.pop["_id", None]
f.write[str[mydict1] + '\n']
f.close[]
answered Oct 16, 2019 at 9:45
Various equivalent methods
Using print
print
already appends a newline by default!
with open["out.txt", "w"] as f:
print["First", file=f]
print["Second", file=f]
Equivalently:
with open["out.txt", "w"] as f:
print["First\nSecond", file=f]
To print
without automatically adding a newline, use sep=""
[since sep="\n"
is the default]:
with open["out.txt", "w"] as f:
print["First\nSecond\n", sep="", file=f]
Using f.write
For files opened in text mode:
with open["out.txt", "w"] as f:
f.write["First\nSecond\n"]
For files opened in binary mode, the files will be written without automatic translation of \n
to the platform-specific line terminator. To enforce the newline character for the current platform is used, use
os.linesep
instead of \n
:
with open["out.txt", "wb"] as f:
f.write["First" + os.linesep]
f.write["Second" + os.linesep]
Output file
Visually:
First
Second
On Linux, the newlines will be separated by \n
:
First\nSecond\n
On Windows, the newlines will be separated by \r\n
:
First\r\nSecond\r\n
To avoid automatic translation of \n
to \r\n
for files opened in text mode, open the file using
open["out.txt", "w", newline="\n"]
.
answered Aug 23 at 6:04
Mateen UlhaqMateen Ulhaq
22.2k16 gold badges86 silver badges127 bronze badges