Read a Text File and Display Each Word Separated by # (CBSE 083)

⚡ Direct Answer & Key Takeaway

To read a text file line by line and display each word separated by `#` (classic CBSE 083 question), open the file in `'r'` mode, iterate over every line, split each line into a list of words with `line.split()`, and print `'#'.join(words)` (plus a trailing `#` if required by the prompt). Using `split()` and `'#'.join()` collapses multiple spaces and removes stray `'\n'` characters cleanly instead of leaving double `##` symbols.

1. Why '#'.join(line.split()) Outperforms str.replace(' ', '#')

Students often attempt this CBSE problem by writing `line.replace(' ', '#')`, which fails whenever a file contains multiple consecutive spaces, tabs, or blank lines. For instance, `'Code Python\n'` becomes `'Code###Python\n'` with ugly repeated hashes and a hidden newline. Calling `line.split()` with no separator argument automatically trims leading and trailing whitespace, collapses runs of spaces or tabs into a single boundary, and strips the trailing `'\n'`. Passing the resulting word list to `'#'.join(words)` places exactly one `#` between adjacent words on that line. If a line in the file is completely blank, `line.split()` returns an empty list `[]`, so checking `if words:` lets you skip empty lines rather than printing stray blank rows or isolated `#` characters.

  • `str.replace(' ', '#')` produces double `##` when two spaces appear together.
  • `line.split()` removes tabs, trailing newlines, and extra spaces in one step.
  • Guarding with `if words:` prevents printing empty lines when a file has blank separators.

2. Trailing Hash vs Between-Words Formatting in CBSE Marking Schemes

Carefully read the sample output in your CBSE question paper because two slightly different formatting variants appear across past papers. In the first variant, words on each line are joined only between words (`Rose#is#red`), produced directly by `print('#'.join(words))`. In the second variant, every word is followed by `#` (`Rose#is#red#`), which matches printing `word + '#'` inside an inner loop (`for word in words: print(word, end='#')`) followed by `print()` at the end of each line. Knowing both patterns allows you to adapt in seconds during the exam. Never leave `end='#'` without a closing `print()` per line if the prompt expects line-by-line output; otherwise every line in the file merges onto a single unbroken row.

  • Use `print('#'.join(words))` when `#` should appear strictly between words (`A#B#C`).
  • Use `for w in words: print(w, end='#')` plus `print()` when a trailing `#` is expected (`A#B#C#`).
  • Forgetting the end-of-line `print()` merges all file lines into a single line.

3. Preserving Line Structure vs Flattening the Whole File

Notice the operational difference between calling `f.read().split()` once versus calling `line.split()` inside a `for line in f:` loop. Reading the entire file with `f.read().split()` treats newlines just like spaces, flattening the whole passage into a single `#`-separated stream across all lines. By contrast, iterating `for line in f:` preserves the original line breaks of the text file so line 1 prints on row 1 and line 2 prints on row 2. Most CBSE 083 marking schemes show line-by-line iteration using `readlines()` or `for line in f:` specifically to preserve each line's boundary. Checking the sample input and sample output in the prompt tells you immediately whether multi-line preservation or single-line flattening is expected.

  • Looping `for line in f:` preserves original line breaks across output rows.
  • Calling `f.read().split()` flattens all lines into one continuous `#`-separated sequence.
  • Always inspect the question paper's sample output to verify single-line vs multi-line formatting.

4. Read File Line by Line and Print Words Separated by #

import os
import tempfile

def display_hash_separated(filepath):
    with open(filepath, "r", encoding="utf-8") as f:
        for line in f:
            words = line.split()
            if words:
                print("#".join(words) + "#")

sample_content = (
    "Data   files store records\n"
    "\n"
    "Python splits words cleanly\n"
    "CBSE 083 Practice\n"
)

with tempfile.TemporaryDirectory() as tmp_dir:
    file_path = os.path.join(tmp_dir, "data.txt")
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(sample_content)

    display_hash_separated(file_path)

Verified Console / Dry-Run Output:

Data#files#store#records#
Python#splits#words#cleanly#
CBSE#083#Practice#

5. Comparison of Methods to Format Words With #

Input Lineline.replace(' ', '#')'#'.join(line.split())'#'.join(words) + '#'
'Data files\n''Data###files\n''Data#files''Data#files#'
'CBSE 083\n''CBSE#083\n''CBSE#083''CBSE#083#'
' Leading space\n''##Leading#space\n''Leading#space''Leading#space#'
'\n' (Blank line)'\n'Skipped (with if words:)Skipped (with if words:)
🎯 1-on-1 Live Mentorship & Free Study Kit

Get Free 1:1 CBSE Python Practice

Master Python string splitting, file iteration, and CBSE 083 practical patterns in 1-on-1 or 1:4 Micro-Pods at 4Achievers Junior.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Using line.replace(' ', '#'), which creates multiple consecutive hashes like 'Data###files' when extra spaces exist.
  • Avoid Mistake: Forgetting to strip '\n' or call split(), leaving newline breaks inside joined output strings.
  • Avoid Mistake: Printing with end='#' inside the word loop without calling print() after each line, merging all lines together.
  • Examiner / Mentor Tip: Mention that join() requires all list elements to be strings, which split() naturally guarantees.
  • Examiner / Mentor Tip: Check the question paper's sample lines carefully to decide between A#B#C and A#B#C#.
  • Examiner / Mentor Tip: Remind examiners that line.split() safely discards trailing newline characters without calling rstrip('\n').

7. Interactive Concept Check Quiz

Question: What does `'#'.join(" Hi all\n".split())` evaluate to in Python?

8. Frequently Asked Questions

Why shouldn't I use line.replace(' ', '#') for this CBSE question?
Because str.replace(' ', '#') replaces every individual space, turning three spaces into '###' and leaving tabs and '\n' untouched. line.split() collapses all whitespace cleanly.
Should the last word on each line also be followed by a '#' symbol?
Look at the sample output in the exam prompt: use '#'.join(words) for A#B#C, or '#'.join(words) + '#' (or end='#' in a loop) for A#B#C#.
What happens if the text file contains blank lines?
Checking if words: skips empty lists produced by blank lines so your program does not print stray empty rows or isolated '#' marks.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class