Count the characters, words, sentences and vowels in a piece of Python text.
Each count needs a different tool, and choosing the right one is the skill being tested.
import re
text = "Python is easy-to-learn, and it's fast."
print(len(text)) # 39 characters
print(len(text.split())) # 6 whitespace-separated words
print(len(re.findall(r"[A-Za-z']+", text))) # 8 word-like tokens
print(len(re.findall(r"[.!?]", text))) # 1 sentence
print(sum(1 for c in text.lower() if c in "aeiou")) # 10 vowelsThe character count is simply the length of the string, which counts code points rather than bytes, so an accented letter counts as one.
The two word counts differ, and the difference is the interesting part. split() splits on whitespace and keeps the punctuation attached to each word, so easy-to-learn, comes out as one piece. The regular expression finds runs of letters and apostrophes, so easy-to-learn becomes three tokens and the trailing comma disappears. Neither is wrong — you have to decide what a word means for your data.
Counting sentences with a regex over the punctuation marks is a quick approximation, but it is fooled by an abbreviation or a decimal point. A real sentence splitter needs a library, which is worth saying out loud rather than pretending the regex is exact.
The vowel count uses a generator expression inside sum, which is the idiomatic way to count items that satisfy a condition. The alternative, text.lower().count("a") summed over each vowel, is more readable for a beginner and roughly the same speed.