How to Process Text Lines with Lists and Loops in Python

This code processes a list of text lines by stripping whitespace, converting to uppercase, and reporting character counts per line and totals.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

28 lines
Python 3.9+
def process_text(lines):
    """Convert a list of text lines to uppercase and report line statistics."""
    processed = []
    total_chars = 0
    
    for index, line in enumerate(lines, start=1):
        cleaned = line.strip().upper()
        processed.append(cleaned)
        total_chars += len(cleaned)
        print(f"Line {index}: {len(cleaned)} characters")
    
    print(f"\nTotal lines: {len(processed)}")
    print(f"Total characters: {total_chars}")
    return processed


if __name__ == "__main__":
    sample_text = [
        "  hello world  ",
        "python is fun",
        "  learn by doing  ",
        "code every day",
    ]
    
    result = process_text(sample_text)
    print("\nProcessed output:")
    for line in result:
        print(f"- {line}")

Output

stdout
Line 1: 10 characters
Line 2: 14 characters
Line 3: 15 characters
Line 4: 13 characters

Total lines: 4
Total characters: 52

How it works

The enumerate function with start=1 provides a 1-based line index, making output readable. Each line is stripped of surrounding whitespace using .strip() and converted to uppercase with .upper(). The length of the cleaned line is computed via len(). Accumulating counts into total_chars and storing results in a list allows later use. The function returns the processed list, and the if __name__ == "__main__" guard ensures the demo runs only when the script is executed directly.

Common mistakes

  • Forgetting to use `enumerate` and manually tracking the index.
  • Not stripping whitespace, causing incorrect character counts.
  • Using `print` inside the loop when you need to collect results for later use.

Variations

  1. Use a list comprehension with `map` to apply transformations, e.g., `[line.strip().upper() for line in lines]`.
  2. Use `re` module to remove punctuation instead of just stripping whitespace.

Real-world use cases

  • Preprocessing user-generated text in a web form before storing it in a database.
  • Normalizing log file lines to uppercase for consistent analysis.
  • Cleaning and reporting stats on lines read from a configuration file or CSV.

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.