Words shorter than 5 characters

EasyFile Handling Programs · 37 of 38

Write a Python program to display the words of a file that have fewer than 5 characters.

Advertisement
Output
['is', 'a', 'very', 'good', 'tool', 'for', 'test']

Approach

  1. Filter words by len(w) < 5.

Solution

Python
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']
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs