Find the bug · #50 · Strings and dates Easy Python
The word count is too high
A 280-word limit blocks posts that are well under it, and an empty post has “1 word”.
On this page
The report
Posts have a 280-word limit. People get “too many words” on posts that are clearly shorter, especially ones pasted from elsewhere, and an empty post shows “1 word”.
The code
Read it first: what should it do? Then click the line where you think the bug is.
def word_count(text):
"""Number of words in a post, for the 280-word limit."""
return len(text.split(" "))Read it, then pick a line.
What does "a b".split(" ") give, with two spaces?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
print(word_count("Ship it today"))
print(word_count("Ship it today "))
print(word_count(""))It prints
3 6 1
It should print
3 3 0
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 splits on exactly one space. Two spaces in a row produce an empty word between them, a trailing space adds an empty word at the end, and an empty post is [""], one “word”. Newlines and tabs aren’t split at all. split() with no argument splits on any run of whitespace and drops the empty pieces.
The fix
1def word_count(text):2 """Number of words in a post, for the 280-word limit."""3 return len(text.split(" "))3 return len(text.split())How you’d find it
- Reproduce with what pasted text looks like: double spaces and a trailing space. Three words count as six.
- Print the split:
["Ship", "", "it", "", "today", ""]. The extra “words” are empty strings. - Check the empty post too:
"".split(" ")is[""]. Both point at splitting on a single space.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
assert word_count("a b\nc ") == 3
assert word_count("") == 0
assert word_count("one") == 1Where else this bites
- JavaScript: use
text.trim().split(/\s+/), and handle the empty string separately. - Counting CSV fields with
split(",")when values can contain commas.