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.
Python code
28 linesdef 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
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
- Use a list comprehension with `map` to apply transformations, e.g., `[line.strip().upper() for line in lines]`.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.