Concepts / Handling Whitespace in Strings

Handling Whitespace in Strings

startswith() checks if a string begins with a specific prefix and returns True or False—it does not search for the substring anywhere in the string.

  • Programming

The Hidden Newline

A line read from a file may look like ordinary text, but it commonly includes a newline character at its end. That character is invisible when you look at the string, yet it affects what happens when the line is printed. If print() receives a line that already ends with a newline, the line supplies one newline and print() adds another. The result is an unwanted blank line between displayed lines.

What do you think happens?

A file line contains the text "From: Sam" followed by its newline character. What happens when print() displays that line?

  • It displays one line with normal spacing
  • It displays the text with double spacing
  • It removes the newline automatically
  • It prints nothing
Reveal answer

Answer: It displays the text with double spacing

The newline stored in the file line is printed as part of the string, and print() adds its own newline after the string.

printed as storedalready includedadded automaticallyFrom: Samtext plus newlineDisplayed linetext plus two newlinesFile newlinefirst newlineprint() newlinesecond newline
What happens when a file line already contains a newline character and print() adds another one?

Checking a Prefix

The startswith() method checks whether a string begins with a specified prefix. It returns True when the prefix is at the beginning of the string and False otherwise. It does not search for that text anywhere else in the string.

python
Output (expected)
True
False
False

The first call returns True because From: is at the beginning of the string. The second call returns False because Sam is not the beginning. The third call also returns False: although the text contains the word from in a later position, startswith() only examines the beginning of the string.

startswith("From:")startswith("From:")From: Samstarts with From:Trueprefix found at startMessage from SamFrom: is not at startFalseprefix not found at start
What is the difference between a prefix match at the start of a string and the same text appearing later?

Removing Trailing Characters

The rstrip() method removes trailing whitespace and newline characters from the right end of a string. It can remove spaces, tabs, and newlines together, which makes it more readable and practical than manually slicing off only the last character.

python
Output (expected)
From: Sam
True

In this example, rstrip() produces a new cleaned string without the trailing newline. The visible text remains From: Sam, but printing the cleaned string no longer carries the file line's extra newline into the output.

inputreturns cleaned stringFrom: Samtrailing newlinerstrip()remove trailing whitespaceFrom: Samno trailing newline
What changes in a string when rstrip() removes characters from its right end?

Filtering File Lines

A common file-processing workflow is to read lines in a for loop, remove their trailing whitespace with rstrip(), and then test the cleaned line with startswith(). If the test returns True, the line is displayed. This is useful when different lines have different prefixes, such as From:, Subject:, To:, or Date: in email files, or ERROR:, WARNING:, and INFO: in log files.

Select From Lines

Given several file lines, display only the lines that begin with From: and avoid extra blank lines.

Read one line: The for loop receives a line from the file. The line includes its trailing newline character.

Clean the line: Call rstrip() to remove trailing whitespace and newline characters before displaying the line.

Check the prefix: Call startswith("From:") to determine whether the cleaned line begins with the required prefix.

Display a match: Only a line that passes the prefix check is printed, so unrelated lines are not included.

The workflow extracts the requested From: lines and displays them with single spacing.

for line in file: line = line.rstrip() if line.startswith("From:"): print(line)

readcleaned textTrueFalseFile linetext plus newlinerstrip()remove trailing charactersstartswith("From:")prefix testPrinted lineclean outputSkipped linenot selected
How does each line move through prefix checking, trailing-whitespace removal, and display?
inspectTrueFalseCurrent lineafter rstrip()Prefix teststarts with From:print(line)selected outputNext linenot printed
How does each input line branch depending on whether startswith() returns True or False?

Common Mistakes

  • Treating startswith() as a general search method

    The requested text is not at the beginning of the string, so startswith() returns False even though related text appears later.

    Fix: Use startswith() when the position at the beginning matters; do not expect it to find a substring anywhere.

  • Printing file lines directly

    Each file line already includes a trailing newline, and print() adds another newline.

    Fix: Call rstrip() on the file line before printing it.

  • Removing only one final character manually

    A line can contain multiple trailing whitespace characters, including spaces, tabs, or newlines.

    Fix: Use rstrip(), which removes trailing whitespace and newline characters together.

  • Checking every line without filtering

    The code cleans the output but displays lines with every prefix.

    Fix: Add a startswith() condition when only a particular type of line is needed.

Try the Workflow

EASY

Write a loop that reads lines from a file, removes trailing whitespace, and prints only lines beginning with "ERROR:".

Hints
  • Process the file one line at a time with a for loop.
  • Assign the result of line.rstrip() back to line.
  • Use if line.startswith("ERROR:") before print(line).
python
Output (expected)
Only cleaned lines beginning with ERROR: are displayed.

Key Takeaways

  1. startswith() checks only whether a string begins with a specified prefix and returns True or False.
  2. File lines include trailing newline characters, so printing them directly can create double spacing.
  3. rstrip() removes trailing whitespace and newline characters from the right end of a string.
  4. A practical filtering pattern is to call rstrip(), test startswith(), and print only matching lines.
  5. This pattern is useful for structured text such as email files and log files, where prefixes identify different kinds of lines.

Key Takeaways

  • Use startswith() for prefix matching, not for searching anywhere within a string.
  • A file line may already contain a newline before print() adds its own.
  • Use rstrip() to remove trailing whitespace and prevent double-spaced output.
  • Combine rstrip() and startswith() in a loop to cleanly filter and display selected lines.