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?
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.
\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.
The new line character in Python is \n . It is used to indicate the end of a line of text.
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.
"\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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With