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.
Python code
23 linestext = """ 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
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
- Use a list comprehension: `processed = [{'original': line, 'stripped': line.strip(), 'word_count': len(line.strip().split())} for line in lines]`.
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.