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.
Python code
21 linesdef 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
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
- 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
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.