String Methods: find() and in Operator
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.
Try it: String methods, character by character
How Python's str methods (split, strip, replace, find, count, startswith, join, in …) scan a string character by character — and that each call returns a new value while the original string never changes.
How it works
- Each method call reads the string it is called on from left to right (strip also trims from the right end).
- split() with no separator skips runs of whitespace and never returns empty strings; split(sep) cuts at every occurrence of sep and can return empty pieces; maxsplit limits the number of cuts.
- find, index, count, replace and `in` slide a window along the string; occurrences never overlap, find gives -1 and index raises ValueError when nothing matches.
- strip(chars) removes any of the given characters (a set, not a substring) from the ends until it meets one that is not in the set.
- Strings are immutable: every call returns a new str, list, int or bool, and the next call in the chain works on that new value.
Default run (62 steps): s = ' Apples, pears,,figs '. Evaluate ' | '.join(s.strip().lower().split(',')) one method call at a time, left to right. … ' | '.join(s.strip().lower().split(',')) → 'apples | pears | | figs'. And s is still ' Apples, pears,,figs '.
Simplified: Printable ASCII text up to 30 characters and up to four chained calls with short arguments. CPython searches with a faster algorithm (fastsearch) than the window-by-window scan shown, but the results are the same.
Loading the simulation…
Why File Output Gets Extra Spacing
A line read from a file normally includes its trailing newline character. When that line is passed to print(), the existing newline in the string remains, and print() adds another newline after the string. The output therefore contains two newline characters, which appears as a blank line between displayed file lines.
Checking a Prefix
The startswith() method checks only the beginning of a string. It receives a prefix, such as 'From:', and returns either True or False. It does not search for that text everywhere in the string. A line beginning with 'From:' matches, while a line containing 'From:' later in the text does not match the prefix check.
The condition selects the line because the requested prefix is at position zero, the beginning of the string. A string that merely contains the same characters somewhere else does not satisfy this particular check.
Cleaning the Line Before Display
rstrip() removes trailing whitespace and newline characters from the end of a string. It can remove multiple trailing spaces, tabs, or newlines at once, making it more readable than manually slicing off one character.
After rstrip(), the line no longer carries its trailing newline for print() to display. print() still adds its normal single newline, so the result appears as one clean output line rather than a line followed by a blank line.
Filtering and Formatting Together
Extracting From: Lines
Process file lines and display only lines that begin with 'From:', without double spacing.
- 1Read one line
A for loop receives each file line, and that line includes its trailing newline character.
- 2Clean the line
Call
rstrip()first so the line no longer carries trailing whitespace or newline characters into the output. - 3Check the prefix
Use
startswith('From:')to test whether the cleaned line begins with the required prefix. - 4Display matching lines
Print the line only when the prefix check returns True. Since the trailing newline was removed,
print()produces single-spaced output.
The workflow selects only the required prefixed lines and displays them without extra blank lines.
Method Names in This Topic
The supplied material gives the detailed behavior needed for startswith() and rstrip(): startswith() performs a beginning-of-string prefix check, while rstrip() removes trailing whitespace and newline characters. The source pack does not define the behavior or result format of find() or the in operator, so their detailed comparison is outside the factual scope of this article. Do not assume that startswith() is a general search operation merely because the topic names other string-search tools.
Common Filtering Mistakes
Common mistake Treating startswith() as a search for text anywhere in the string
What it looks likeA line such as "Message From: sender" is expected to match startswith("From:").
Why it failsstartswith()checks only the beginning of the string, not a later occurrence.Do this insteadUse startswith() when the target must be the prefix of the line.
Common mistake Printing a file line without removing its trailing newline
What it looks likeprint(line)Why it failsThe file line already contains a newline, and
print()adds another one.Do this insteadCall line.rstrip() before printing.Common mistake Removing only one final character manually
What it looks likeline[:-1]Why it failsThe line may contain multiple trailing whitespace characters, including spaces, tabs, or newlines.
Do this insteadUse rstrip(), which removes trailing whitespace and newlines together.
Common mistake Filtering before considering output cleanup
What it looks likeif line.startswith("From:"): print(line)Why it failsThe prefix check can succeed, but the original newline still causes double spacing when the line is printed.
Do this insteadClean the line with rstrip() first, then perform the prefix check and print the cleaned line.
Practice
Write a loop that processes file lines, removes trailing whitespace and newline characters, and prints only lines beginning with 'Subject:'. Explain why calling rstrip() affects the appearance of the output.
Hints
- Call
rstrip()on each line before testing or printing it. - Use
startswith('Subject:')as the condition. - Print the cleaned line only when the condition is True.
Key Takeaways
- 1
startswith()checks whether a string begins with a specified prefix and returns True or False. - 2A file line includes a trailing newline, and
print()adds another newline when displaying it. - 3
rstrip()removes trailing whitespace and newline characters, preventing double-spaced output. - 4A practical file-processing pattern is to call
rstrip(), teststartswith(), and print only matching lines. - 5The supplied material does not define
find()or the in operator, so their detailed behavior should not be inferred from thestartswith()rule.
At a glance
- Use
startswith()for prefix filtering, not for finding the same text later in a string. - Remember that file lines carry their own trailing newline character.
- Use
rstrip()before printing to remove trailing whitespace and avoid double spacing. - Combine
rstrip()andstartswith()in a loop to extract clean, selected lines from structured text files.