Bird
0
0

What will be the output of this code if 'test.txt' contains:\nLine1\nLine2\n\nLine4\n?

medium📝 Predict Output Q13 of 15
Python - File Reading and Writing Strategies
What will be the output of this code if 'test.txt' contains:\nLine1\nLine2\n\nLine4\n?
with open('test.txt') as f:
    for line in f:
        print(line.strip())
ALine1\nLine2\n\nLine4
BLine1\nLine2\n\n\nLine4
CLine1\nLine2\nLine4
DLine1\nLine2\nLine4\n
Step-by-Step Solution
Solution:
  1. Step 1: Understand strip() effect on lines

    strip() removes whitespace including newlines, so empty lines become empty strings.
  2. Step 2: Analyze printing each stripped line

    Empty lines print as blank lines, but print() adds a newline, so empty lines show as blank lines.
  3. Final Answer:

    Line1\nLine2\n\nLine4 -> Option A
  4. Quick Check:

    strip() on empty -> '', print('') = blank line = Line1\nLine2\n\nLine4 [OK]
Quick Trick: strip() removes newlines, print adds one newline per line [OK]
Common Mistakes:
  • Assuming strip() keeps newlines
  • Confusing blank lines with extra newlines
  • Ignoring print() adds newline automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes