concept newline character in category python

appears as: newline character, newline characters
Get Programming: Learn to code with Python

This is an excerpt from Manning's book Get Programming: Learn to code with Python.

Figure 19.1. Converting a string of characters into words. In the top example named start, you can keep track of where you are in the character string by using a start and end pointer. In the middle example named found word, you stop changing end when you reach a newline character. In the bottom example named start next, you reset the start and end pointers to the character right after the newline.
Figure 19.1. Converting a string of characters into words. In the top example named start, you can keep track of where you are in the character string by using a start and end pointer. In the middle example named found word, you stop changing end when you reach a newline character. In the bottom example named start next, you reset the start and end pointers to the character right after the newline.

With this simple sketch, you can already see how to achieve this task. The start and end pointers start at the beginning of the big string. As you’re looking for a newline character to mark the end of the word, you’ll increment the end pointer until you find the \n. At that point, you can store the word from the start pointer to the end pointer. Then, move both pointers to one index past the newline character to start looking for the next word.

It’s important that each piece of information is on a separate line, implying that your program will have a newline character as the final character on each line. Python has a way to deal with this, as you’ll soon see. Knowing this is the format, you can read the file line by line. You store every other line, starting with the first line, in a tuple. Then you store every other line, starting with the second line, in another tuple. The tuples look like this:

23.1.3. Remove the newline character

When you’re reading a line from the file, the line contains all the characters you can see plus the newline character. You want to store everything except that special character, so you need to remove it before storing the information.

Because each line you read in is a string, you can use a string method on it. The easiest thing to do is to replace every occurrence of \n with the empty string “”. This will effectively remove the newline character.

The following listing shows how to replace a newline character with an empty string and save the result into a variable.

Listing 23.1. Remove the newline character
word = "bird\n"                                      #1
print(word)                                          #2
word = word.replace("\n", "")                        #3
print(word)                                          #4
Thinking like a programmer
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest