A draft editor shows approximate word and character counts for a text excerpt.
What You Need to Understand
A word counter can split text on whitespace and count resulting tokens. A character counter can measure len(text), but it counts Unicode code points, not necessarily visible glyphs.
When to Use It
A draft editor shows approximate word and character counts for a text excerpt.
Step-by-Step Python Example
text = "Python code is readable."
words = text.split()
print("Words:", len(words))
print("Characters:", len(text))
print("Characters without spaces:", len(text.replace(" ", "")))
How the Example Works
Splitting produces four whitespace-separated parts; the character counts include punctuation unless removed explicitly.
Example Output
Words: 4
Characters: 24
Characters without spaces: 21
3
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
message = " one two\nthree "
print(len(message.split()))
Important Behavior and Edge Cases
A whitespace-based word counter is approximate and treats punctuation-separated phrases differently from linguistic tokenizers. Decide whether line breaks and tabs count as whitespace.
Try It Yourself
Count words in two lines of text and inspect what happens with repeated spaces.
Common Beginner Mistakes
- A whitespace-based word counter is approximate and treats punctuation-separated phrases differently from linguistic tokenizers. Decide whether line breaks and tabs count as whitespace.
- Applying a string method before defining whether text is intended for display, comparison, parsing, or input validation.
Key Takeaways
- A word counter can split text on whitespace and count resulting tokens.
- Splitting produces four whitespace-separated parts; the character counts include punctuation unless removed explicitly.
- A whitespace-based word counter is approximate and treats punctuation-separated phrases differently from linguistic tokenizers.