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.
Python code
23 linestext = "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
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
- Use `text.split(' ')` to split on single spaces, but this breaks on multiple spaces.
- 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
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.