How to Process Lines of Text in Python

Strip whitespace, split a multi-line string, count words per line, and print structured summaries using basic string methods and loops.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

23 lines
Python 3.9+
text = """   Python is great!
Coding is fun.
   Python skills help you grow.   """

lines = text.strip().splitlines()
line_count = len(lines)

processed = []
for line in lines:
    stripped = line.strip()
    word_count = len(stripped.split())
    processed.append({
        "original": line,
        "stripped": stripped,
        "word_count": word_count
    })

print("Line count:", line_count)
for i, entry in enumerate(processed, start=1):
    print(f"Line {i}: '{entry['stripped']}' | words: {entry['word_count']}")

total_words = sum(entry["word_count"] for entry in processed)
print("Total words:", total_words)

Output

stdout
Line count: 3
Line 1: 'Python is great!' | words: 3
Line 2: 'Coding is fun.' | words: 3
Line 3: 'Python skills help you grow.' | words: 5
Total words: 11

How it works

text.strip() removes surrounding whitespace so blank leading/trailing lines are ignored, then splitlines() splits on newline characters into a list of raw lines. Looping over that list lets you process each line individually, and calling strip() again per line removes indentation or trailing spaces. str.split() without arguments splits on any whitespace and returns a list of words, whose length is the word count. Summing the per-line word counts gives the total words.

Common mistakes

  • Using `split()` on the whole text instead of `splitlines()` — that splits on whitespace, butchering multi-word lines.
  • Forgetting to call `strip()` per line, so leading spaces inflate the line or word counts.
  • Assuming line indexes start at 0 in human-readable output; `enumerate(start=1)` fixes that.
  • Expecting `splitlines()` to handle whitespace-only lines; an empty stripped line yields 0 words, which may need filtering.

Variations

  1. Use a list comprehension: `processed = [{'original': line, 'stripped': line.strip(), 'word_count': len(line.strip().split())} for line in lines]`.
  2. Read lines from a file directly with `open('file.txt').read().splitlines()` instead of a hardcoded string.

Real-world use cases

  • Parsing multi-line log files to count words or extract cleaned content per line for analysis.
  • Preprocessing user-provided text (like comments or essays) by trimming whitespace and computing line-level stats.
  • Formatting plain-text reports or markdown snippets where each line needs consistent trimming and word-count summaries.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.