Home / Python / Example programs / Strings

Python program: Count lines, words and characters

Count the lines, words and characters in a block of text, like the Unix wc command.

The code

text = """Python is easy to read.
It is used for data science,
web apps and automation."""

lines = text.splitlines()
words = text.split()
print(len(lines), "lines")
print(len(words), "words")
print(len(text), "characters")
print("average word length:", round(sum(len(w.strip(".,")) for w in words) / len(words), 1))

Output

3 lines
15 words
77 characters
average word length: 4.0

How it works

splitlines splits on line breaks and split on any whitespace.

Python features used

Learn the ideas behind it in the free lesson Strings.