How to Process Text with Lists and Loops in Python

A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.

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

Python code

23 lines
Python 3.9+
text = "Python makes text processing easy and fun"

words = text.lower().split()

print("Words in the sentence:")
for index, word in enumerate(words, start=1):
    print(f"{index}. {word}")

filtered_words = [word for word in words if len(word) > 3]

print(f"\nWords longer than 3 characters: {filtered_words}")

letter_count = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0}

for char in text.lower():
    if char in letter_count:
        letter_count[char] += 1

print("Vowel counts:")
for vowel, count in letter_count.items():
    print(f"{vowel}: {count}")

print(f"\nTotal words: {len(words)}")

Output

stdout
Words in the sentence:
1. python
2. makes
3. text
4. processing
5. easy
6. and
7. fun

Words longer than 3 characters: ['python', 'makes', 'text', 'processing', 'easy']
Vowel counts:
a: 1
e: 3
i: 2
o: 3
u: 1

Total words: 7

How it works

The code converts the input to lowercase and splits it into a list of words using split(), which handles whitespace automatically. The enumerate function pairs each word with its index, starting from 1, to print a numbered list. A list comprehension filters words longer than 3 characters, and a dictionary tracks vowel counts by iterating over each character. Finally, len() gives the total word count, wrapping the whole flow in a simple, readable script.

Common mistakes

  • Forgetting to call `.lower()` before counting vowels, causing uppercase letters to be missed.
  • Assuming `split()` splits on commas instead of whitespace — use `split(',')` for CSV text.
  • Modifying the list while iterating over it, which can skip or repeat items.

Variations

  1. Use `text.split(' ')` to split on single spaces, but this breaks on multiple spaces.
  2. Compute vowel counts with `collections.Counter` and a comprehension over vowels.

Real-world use cases

  • Building a quick text stats tool to summarize user-generated content before storage.
  • Enumerating configuration values from a settings file to display numbered options in a CLI.
  • Validating and counting keyword mentions in support tickets to route them to the right team.

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.