Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between \n and \r\n in python

Tags:

python

utf-8

I have a script that sometimes prints a newline as \n and sometimes uses \r\n. What is the difference between the two, and is one preferable over the other?

like image 430
David542 Avatar asked Jan 30 '15 02:01

David542


People also ask

Are \n and \r the same?

The /r stands for return or carriage return which owes it's history to the typewriter. A carriage return moved your carriage all the way to the right so you were typing at the start of the line. The /n stands for new line, again, from typewriter days you moved down to a new line.

What does \n and \r mean?

\n means new line. It means that the cursor must go to the next line. \r means carriage return. It means that the cursor should go back to the beginning of the line.

What do \n do in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text.

What is the difference between New Line and carriage return?

A carriage return would do exactly that, return the print head carriage to the beginning of the line. A newline character would simple shift the roller to the next line without moving the print head.


2 Answers

"\n" is the class Unix/linux style for new line. "\r\n" is the default Windows style for line separator. "\r" is classic Mac style for line separator. I think "\n" is better, because this also looks good on windows, but some "\r\n" may not looks so good in some editor under linux, such as eclipse or notepad++. If you are handling some protocols, the "\r\n" is usually required.

like image 84
Cui Heng Avatar answered Sep 19 '22 19:09

Cui Heng


Code

print "\n",
print "\r",
print "\r\n",

gives you the following output in hex

0a 0d 0d 0a

See also answers here and here.

like image 22
dmitri Avatar answered Sep 18 '22 19:09

dmitri