How to Process Text with Lists and Loops in Python

Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.

Easy Python 3.6+ Aug 9, 2026 Lists & loops 17 views 0 copies

Python code

19 lines
Python 3.6+
# text_processor.py

def process_text(lines):
    """Count words, show uppercase, and count characters per line."""
    total_words = 0
    print("Line-by-line analysis:")
    for i, line in enumerate(lines, start=1):
        words = line.split()
        total_words += len(words)
        print(f"  Line {i}: {len(words)} words, {len(line)} chars, UPPER: {line.upper()}")
    print(f"Total words: {total_words}")

if __name__ == "__main__":
    sample_lines = [
        "hello world",
        "pythonskillset is fun",
        "learn lists and loops"
    ]
    process_text(sample_lines)

Output

stdout
Line-by-line analysis:
  Line 1: 2 words, 11 chars, UPPER: HELLO WORLD
  Line 2: 3 words, 20 chars, UPPER: PYTHONSKILLSET IS FUN
  Line 3: 4 words, 22 chars, UPPER: LEARN LISTS AND LOOPS
Total words: 9

How it works

The enumerate function pairs each line with its index starting at 1, giving you both the line number and the text. line.split() splits on whitespace, so it counts words regardless of extra spacing. len(line) returns the raw character count including spaces. The f-string formatting embeds variables directly for readable output. Calling process_text inside the if __name__ == "__main__" guard lets the script run standalone without executing when imported.

Common mistakes

  • Using `range(len(lines))` instead of `enumerate`, which forces manual index tracking
  • Counting characters with `len(line.split())` instead of `len(line)` for total characters
  • Forgetting the `start=1` argument, so line numbers start at 0 instead of 1

Variations

  1. Use a list comprehension to collect results and print them later
  2. Read lines from a file with `open()` instead of a hardcoded list

Real-world use cases

  • Analyzing log files to summarize word counts per line for debugging.
  • Generating formatted reports from customer feedback lines in a support tool.
  • Preprocessing free-text input fields before saving them to a database.

Sponsored

Run this sample

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

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.