[Tutor] Newline

Steven D'Aprano steve at pearwood.info
Sat Dec 4 03:09:09 CET 2010


Ashley Blackwell wrote:
> Hello everybody, I'm new to the mailing list so I'm pretty sure I'll have
> lots of questions:)
> 
> It's a very basic question I have and everybody might look at this
> question and say, "Wow, she reallly doesn't get it?" But oh well. Here's my
> question: I'm in Chapter 2 of my Python Programming Third Editition book.
> I've gotten to the section of the chapter where it talks about a "newline
> character. Exactly what is a newline character? 

Text (say, in a word processor, or in source code) is made up of 
characters. Some characters are visible, like letters and digits. Some 
characters are invisible "whitespace". The most obvious one is the space 
character, which you get by pressing the spacebar. A little less obvious 
is the "newline" character, which you get by pressing the Enter key.

The newline is special, because it instructions your word processor or 
text editor to start a new line. Duh! :-)

Anyway, the point is that when you're dealing with text, there is an 
"invisible" newline at the end of each line. That's how your program 
knows that it is the end of a line!

The print() function automatically adds a newline by default:

 >>> s = "Nobody expects the Spanish Inquisition!"  # no newline
 >>> print(s)  # automatically adds a newline
Nobody expects the Spanish Inquisition!
 >>>


If the string already includes a newline, you get a blank line:

 >>> s = "Nobody expects the Spanish Inquisition!\n"  # \n = newline
 >>> print(s)
Nobody expects the Spanish Inquisition!

 >>>

Notice the blank line between the printed string and the next prompt (>>>)?

print() adds a newline because that's nearly always what you want:

 >>> for i in (1, 2, 3):
...     print(i, "spam")
...
1 spam
2 spam
3 spam


but sometimes you want to print on the same line:

 >>> for i in (1, 2, 3):
...     print(i, "spam", end="***")
...
1 spam***2 spam***3 spam***>>>

Notice that because there's no newline printed at all, the prompt >>> 
ends up on the same line as the output! There are ways around that. 
Here's one:


 >>> for i in (1, 2, 3):
...     print(i, "spam", end="\n" if i==3 else "***")
...
1 spam***2 spam***3 spam
 >>>



Hope this helps,



-- 
Steven


More information about the Tutor mailing list