PCAP Strings Practice Question
A cloud infrastructure engineer is developing a Python script to parse large configuration files from a fleet of servers. Each file can be up to 500 MB. The script reads the file line by line using a file object, strips comment lines (those starting with '#'), and accumulates only the configuration directives into a single string for further processing. The current code is:
```python result = ''
with open('config.cfg') as f:
for line in f:
if not line.startswith('#'):result += line.strip() ```
After processing just a few hundred lines of a large file, the script becomes extremely slow and consumes an excessive amount of memory. The engineer identifies that string concatenation using `+=` is inefficient because strings are immutable, causing repeated memory reallocation. Which approach should the engineer implement to resolve the performance issue without changing the final output?
⚠ Common exam trap
Candidates often incorrectly believe that `result = result + line.strip()` is more efficient than `result += line.strip()`, but both have the same O(n^2) performance due to string immutability. The correct solution is to collect lines in a list and join them with `''.join()`.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
Use a list to collect stripped lines and then call `''.join(lines)` after the loop.
It avoids the O(n²) time complexity of repeated string concatenation by collecting stripped lines in a list and then joining them once with `''.join(lines)`. This leverages the efficient memory allocation of `str.join`, which precomputes the total size and allocates exactly once, solving the performance and memory issue without altering the final output.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
Replace `result += line.strip()` with `result = result + line.strip()`.
Why it's wrong here
Both statements perform repeated string concatenation: `+=` is simply augmented assignment, and `result = result + line.strip()` is the equivalent binary addition followed by assignment. Because strings are immutable, every iteration allocates a new string and copies the accumulated content, yielding O(n²) time for n lines. Neither syntax changes the underlying quadratic behavior, so this cannot resolve the performance problem.
- ✗
Use `io.StringIO` to write lines and then retrieve content with `.getvalue()`.
Why it's wrong here
`io.StringIO` provides an in-memory text buffer that avoids repeated string concatenation, but writing each stripped line with `.write()` still incurs method-call overhead and the buffer must be drained via `.getvalue()` at the end. While it works, it is an indirect, heavier solution compared to simply accumulating lines in a list and calling `''.join(lines)`. The standard idiom for building a string from known substrings is `str.join`, not a stream wrapper designed for file-like behavior.
- ✗
Use `str.join` called on the file object: `f.join('')`.
Why it's wrong here
`str.join` is a method on the separator string, so the correct call is `''.join(iterable_of_strings)`; invoking `f.join('')` attempts to call a nonexistent `join` method on a file object, raising `AttributeError`. Even if it existed, `f.join('')` would treat the file object as the separator and an empty string as the iterable, which is semantically upside-down. File objects are not iterators of lines for join purposes; you must read lines separately.
- ✓
Use a list to collect stripped lines and then call `''.join(lines)` after the loop.
Why this is correct
Store each stripped line as an element in a list during the loop; appending to a list is amortized O(1). After the loop, call `''.join(lines)` to allocate the final string exactly once and copy each part in a single pass, producing O(n) total work. This is the canonical idiom because it avoids repeated string reallocation and takes advantage of `str.join`'s optimized internal traversal of the sequence.
Visual reference
Go deeper
Related to this question
About these practice questions
This PCAP question is part of Courseiva's 169-question bank — original exam-style content with full explanations and wrong-answer analysis, never real exam questions or exam dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This PCAP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCAP exam.