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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

33 lines
Python 3.9+
def 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

stdout
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

  1. Use `len(text.split())` inline instead of a separate `words` variable for brevity.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.