Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
How to Translate Characters in a String with str.maketrans in Python
Build and apply character translation tables with str.maketrans and str.translate to replace, delete, or remap letters in a Python string.
def translate_demo():
# Build a translation table: a→1, e→2, i→3, o→4, u→5
table = str.maketrans("aeiou", "12345")
text = "Hello, Python world! Keep coding, friend."
translated = text.translate(table)
print(f"Original: {text}")
print(f"Translated: {translated}")
# Example wit…
How to Truncate a String with Ellipsis in Python
A function that shortens text to a maximum length and appends an ellipsis when truncation occurs, handling edge cases.
def truncate_with_ellipsis(text: str, max_length: int) -> str:
"""Truncate text to max_length, appending ellipsis if truncated."""
if len(text) <= max_length:
return text
if max_length <= 3:
return text[:max_length]
return text[: max_length - 3] + "..."
if __name__ == "__main__":
t…
How to Unescape HTML Entities in Python
Convert HTML entities like & and < back to their literal characters using the standard library html module.
import html
def unescape_html_entities(text: str) -> str:
"""Convert HTML entities like & to their character equivalents."""
return html.unescape(text)
if __name__ == "__main__":
sample = "Tom & Jerry <cartoon> "classic" 'fun' © 2024"
result = unescape_html_enti…
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.
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,
…
How to build a text helper in Python for beginners
This code provides easy-to-use functions for cleaning text, removing punctuation, counting word frequencies, and summarizing strings — perfect for beginners.
def clean_text(text: str) -> str:
"""Clean and normalize a text string."""
text = text.strip()
text = text.replace(" ", " ")
text = text.capitalize()
text = text.replace(".", ".")
return text
def remove_punctuation(text: str) -> str:
"""Remove common punctuation marks from a string."""
…
How to parse key=value pairs in Python
Parse a single line of key=value pairs separated by a delimiter into a Python dictionary.
def parse_key_value_pairs(line: str, delimiter: str = "&") -> dict:
"""Parse a single line of key=value pairs into a dictionary."""
pairs = {}
for token in line.split(delimiter):
if not token.strip():
continue
key, _, value = token.partition("=")
pairs[key.strip()] = val…
Normalize unicode accents to ASCII in Python
This code converts accented Unicode characters to ASCII equivalents using the standard library's unicodedata module.
import unicodedata
def normalize_accents(text: str) -> str:
"""Convert accented unicode characters to ASCII equivalents."""
decomposed = unicodedata.normalize('NFD', text)
ascii_text = ''.join(
char for char in decomposed
if unicodedata.category(char) != 'Mn'
)
return unicodedata.n…
Python String Helper Functions for Beginners
A set of beginner-friendly Python functions that count words, reverse text, convert to title case, strip punctuation, and compute character frequency from a string.
def count_words(text):
"""Count the number of words in a string."""
return len(text.split())
def reverse_text(text):
"""Reverse the entire string."""
return text[::-1]
def title_case(text):
"""Capitalize the first letter of each word."""
return text.title()
def remove_punctuation(text):
…
Remove Substring Occurrences Case-Insensitively in Python
This code removes every case-insensitive occurrence of a given substring from a text string using a simple looping approach.
def remove_occurrences_ci(text: str, substring: str) -> str:
"""Remove all case-insensitive occurrences of substring from text."""
if not substring:
return text
result = []
i = 0
lower_text = text.lower()
lower_sub = substring.lower()
sub_len = len(substring)
while i <…
Text Processor Functions for Beginners in Python
Demonstrates simple text-processing utilities: word counting, word reversal, whitespace normalization, and lowercase conversion using basic string methods.
def count_words(text):
"""Return the number of words in a string."""
return len(text.split())
def reverse_words(text):
"""Return the text with words in reverse order."""
return ' '.join(text.split()[::-1])
def remove_extra_spaces(text):
"""Return text with extra whitespace collapsed to a single s…
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.