How to Inspect String Statistics in Python

A beginner-friendly function that returns detailed statistics about a string, including length, word count, character types, and easy text transformations.

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

Python code

21 lines
Python 3.9+
def inspect_text(text: str) -> dict:
    """Return useful stats about a string for beginners."""
    words = text.split()
    return {
        "length": len(text),
        "word_count": len(words),
        "uppercase": sum(1 for ch in text if ch.isupper()),
        "lowercase": sum(1 for ch in text if ch.islower()),
        "digits": sum(1 for ch in text if ch.isdigit()),
        "spaces": text.count(" "),
        "reversed": text[::-1],
        "title_case": text.title(),
        "no_punctuation": ''.join(ch for ch in text if ch.isalnum() or ch.isspace()),
    }


if __name__ == "__main__":
    sample = "Hello, Python Learners! 123"
    result = inspect_text(sample)
    for key, value in result.items():
        print(f"{key}: {value}")

Output

stdout
length: 24
word_count: 4
uppercase: 2
lowercase: 16
digits: 3
spaces: 3
reversed: 321 !srenraeL nohtyP ,olleH
title_case: Hello, Python Learners! 123
no_punctuation: Hello Python Learners 123

How it works

The function uses text.split() to split on whitespace, giving an accurate word count. Character-type counts use generator expressions with methods like isupper() and isdigit(), which handle Unicode correctly. The reversed field uses slicing with [::-1] for a quick string reversal. title_case applies str.title() to capitalize each word's first letter. Finally, no_punctuation filters with a comprehension that keeps only alphanumeric characters and whitespace.

Common mistakes

  • Counting punctuation as part of word_count when splitting only on spaces
  • Assuming `isupper()` works only for ASCII, not Unicode characters
  • Forgetting that `title()` also capitalizes after digits, changing the original text's formatting

Variations

  1. Use `text.split()` with a `maxsplit` parameter to limit word splitting for performance on large strings

Real-world use cases

  • Building a text analysis dashboard that shows basic stats on user feedback or comments.
  • Pre-processing user input to detect unusually short or long strings before storing in a database.
  • Creating a beginner-friendly debugging tool to quickly inspect unexpected string values in logs.

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.