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.
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?
Reveal 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.
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.
True
False
FalseThe 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.
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.
From: Sam
TrueIn 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.
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.
- 1Read one line
The for loop receives a line from the file. The line includes its trailing newline character.
- 2Clean the line
Call
rstrip()to remove trailing whitespace and newline characters before displaying the line. - 3Check the prefix
Call
startswith("From:")to determine whether the cleaned line begins with the required prefix. - 4Display 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)- 1The for loop processes each file line one at a time.
- 2
rstrip()removes trailing whitespace and newline characters from the current line. - 3
startswith("From:")checks whether the cleaned line begins with From:. - 4
print(line)displays only matching lines without the extra spacing caused by the original newline.
Only cleaned lines beginning with From: are displayed.Common Mistakes
Common mistake Treating startswith() as a general search method
What it looks like"Message from Sam".startswith("From:")Why it failsThe requested text is not at the beginning of the string, so
startswith()returns False even though related text appears later.Do this insteadUse startswith() when the position at the beginning matters; do not expect it to find a substring anywhere.
Common mistake Printing file lines directly
What it looks likefor line in file: print(line)Why it failsEach file line already includes a trailing newline, and
print()adds another newline.Do this insteadCall rstrip() on the file line before printing it.
Common mistake Removing only one final character manually
Why it failsA line can contain multiple trailing whitespace characters, including spaces, tabs, or newlines.
Do this insteadUse rstrip(), which removes trailing whitespace and newline characters together.
Common mistake Checking every line without filtering
What it looks likefor line in file: line = line.rstrip() print(line)Why it failsThe code cleans the output but displays lines with every prefix.
Do this insteadAdd a startswith() condition when only a particular type of line is needed.
Try the Workflow
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:")beforeprint(line).
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. - 2File 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. - 4A practical filtering pattern is to call
rstrip(), teststartswith(), and print only matching lines. - 5This pattern is useful for structured text such as email files and log files, where prefixes identify different kinds of lines.
At a glance
- 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()andstartswith()in a loop to cleanly filter and display selected lines.