Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
Find Data From a String in Python: Stats, Clean, Keywords
Three helper functions for beginners: compute character/word/sentence stats, normalize whitespace and case, and extract unique sorted keywords from a string.
def get_text_stats(text):
"""Return basic statistics about a string."""
words = text.split()
sentences = text.replace('!', '.').replace('?', '.').split('.')
sentences = [s for s in sentences if s.strip()]
return {
'characters': len(text),
'words': len(words),
'sentences': le…
How to Sort Text Alphabetically in Python
Sort words or lines alphabetically with case-insensitive ordering while preserving original casing.
def sort_words(text):
"""Sort words alphabetically (case-insensitive), preserving case."""
words = text.split()
return sorted(words, key=str.lower)
def sort_lines(text):
"""Sort lines alphabetically (case-insensitive), preserving case."""
lines = [line for line in text.splitlines() if line.strip(…
How to Sort Text in Python with a Simple Helper Function
A compact helper function that sorts a list of strings or splits a string into words and sorts them alphabetically, with optional reverse ordering.
def sort_text(data, reverse=False):
"""
Sort a list of strings (or a single string split into words) alphabetically.
"""
if isinstance(data, str):
words = data.split()
else:
words = [str(item) for item in data]
return sorted(words, reverse=reverse)
if __name__ == "__main__":
…
Browse by section
Each section groups closely related Python snippets.
Strings & text — Python code examples
What you will find here
This page collects strings & text snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.