Python Practice › File Handling Programs › Program 37
Words shorter than 5 characters
Write a Python program to display the words of a file that have fewer than 5 characters.
Output
['is', 'a', 'very', 'good', 'tool', 'for', 'test']
Approach
- Filter words by
len(w) < 5.
Solution
with open("story.txt", "w") as f: f.write("Python is a very good tool for test automation\n") with open("story.txt") as f: print([w for w in f.read().split() if len(w) < 5])Output
['is', 'a', 'very', 'good', 'tool', 'for', 'test']
Learn the concept
New to this topic? Read the lesson, then come back.