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.
Python code
19 lines# 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
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
- Use a list comprehension to collect results and print them later
- 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
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.