How to Validate Text Input in Python: A Simple Text Processor
A Python function that validates a text string by trimming whitespace, then returns a dictionary with character, word, and sentence counts.
Python code
33 linesdef validate_text(text: str) -> dict:
"""Analyze a text string and return basic validation statistics."""
stripped = text.strip()
if not stripped:
return {
"valid": False,
"reason": "Text is empty or only whitespace",
"characters": 0,
"words": 0,
"sentences": 0,
}
words = stripped.split()
sentence_count = len([c for c in stripped if c in ".!?"])
return {
"valid": True,
"reason": "Text is non-empty",
"characters": len(stripped),
"words": len(words),
"sentences": sentence_count,
}
if __name__ == "__main__":
sample_text = "Hello world! This is Python."
result = validate_text(sample_text)
print(f"Text: '{sample_text}'")
print(f"Valid: {result['valid']}")
print(f"Characters: {result['characters']}")
print(f"Words: {result['words']}")
print(f"Sentences: {result['sentences']}")
print(f"Reason: {result['reason']}")
Output
Text: 'Hello world! This is Python.'
Valid: True
Characters: 28
Words: 5
Sentences: 2
Reason: Text is non-empty
How it works
The strip() method removes leading and trailing whitespace so that a string of only spaces is treated as empty. Splitting on whitespace with split() counts words by breaking on any run of spaces. The sentence count uses a list comprehension that checks each character against a set of punctuation marks. The function returns a dictionary, which makes the result easy to access by key in the caller. The if __name__ == '__main__' guard lets the script run standalone while keeping validate_text importable.
Common mistakes
- Forgetting to strip whitespace, so ' ' is incorrectly counted as valid text.
- Counting sentence endings by character, which fails on abbreviations like 'Mr.' or decimals like '3.14'.
- Assuming `.split()` only splits on single spaces instead of any whitespace sequence.
Variations
- Use `len(text.split())` inline instead of a separate `words` variable for brevity.
- Validate sentence endings with a regex like `re.findall(r'[.!?]+', text)` for more accurate counts.
Real-world use cases
- Checking that a user-submitted comment field has content before saving it to a database.
- Building a quick word-count feature for a note-taking app that shows stats as users type.
- Sanitizing input in a chat bot to reject empty or whitespace-only messages.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.