Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
How to Compare Two Strings in Python
Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.
def compare_data(first_value, second_value):
"""Compare two string values and return a report."""
if first_value == second_value:
status = "MATCH"
else:
status = "DIFFER"
return {
"first_value": first_value,
"second_value": second_value,
"status": status,
…
How to Convert Data to Strings in Python
Convert common data types like bytes, numbers, containers, and None to readable strings with a safe helper function.
def to_str(value):
"""Convert common types to a readable string, safe for beginners."""
if isinstance(value, bytes):
return value.decode("utf-8")
if isinstance(value, (dict, list, tuple, set)):
return str(value)
if value is None:
return ""
return str(value)
if __name__ == …
How to Convert and Process Text in Python
This code cleans, converts, splits, joins, counts, replaces, reverses, and finds substrings in a text string using Python's standard string methods.
text = " hello world, python is fun! "
# Clean up whitespace
cleaned = text.strip()
# Convert to title case
titled = cleaned.title()
# Split into words
words = cleaned.split()
# Join with hyphens
hyphenated = "-".join(words)
# Count occurrences of a letter
letter_count = cleaned.count("o")
# Replace a word
rep…
How to Convert camelCase to snake_case in Python
Convert camelCase strings to snake_case using a simple Python function that inserts underscores before uppercase letters and lowercases everything.
def camel_to_snake(s):
result = ""
for i, char in enumerate(s):
if char.isupper() and i > 0:
result += "_"
result += char.lower()
return result
if __name__ == "__main__":
test_cases = ["camelCase", "helloWorld", "thisIsACoolExample", "already_snake", "UPPER"]
for case i…
How to Convert snake_case to Title Case in Python
Convert snake_case strings to title case by splitting on underscores, capitalizing each word, and joining them with spaces.
def to_title_case(snake_str):
words = snake_str.split("_")
return " ".join(word.capitalize() for word in words)
if __name__ == "__main__":
examples = ["hello_world", "convert_snake_case", "already_title_case", "multiple__under_scores"]
for example in examples:
print(f"{example!r:35} -> {to_tit…
How to Count Vowels in a String in Python
Counts uppercase and lowercase vowels in a given string using a set and a generator expression.
def count_vowels(text):
vowels = set("aeiouAEIOU")
return sum(1 for char in text if char in vowels)
if __name__ == "__main__":
sample = "Hello, World!"
result = count_vowels(sample)
print(f"Vowel count in '{sample}': {result}")
How to Count Words in a String in Python
Split a paragraph on whitespace and return the number of words using Python's built-in string methods.
def count_words(paragraph: str) -> int:
words = paragraph.split()
return len(words)
if __name__ == "__main__":
paragraph = "The quick brown fox jumps over the lazy dog."
result = count_words(paragraph)
print(f"Word count: {result}")
How to Detect Expired Domains Using Python
Parse a list of domain registration data and compare expiry dates to today to find expired domains.
import datetime
# List of test domains with fake registration and expiry dates
# Format: (domain, registration_date, expiry_date)
test_domains = [
('example.com', '2020-01-15', '2024-01-15'), # Expired
('google.com', '1997-09-15', '2026-09-15'), # Still active
('test-site.org', '2019-06-01', '2023-06-0…
How to Detect PII in Documents Using Python
Use regex patterns to automatically detect emails, phone numbers, SSNs, and credit card numbers in text documents.
import re
from typing import List, Dict
def detect_pii(text: str) -> Dict[str, List[str]]:
patterns = {
"email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
"phone": r"\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
"ssn": r"\b\d{3}-\d{2}-\d{4}\b",
"credit_card": r"\b\d{4}[- ]?\d{4}[-…
How to Detect if a String Contains Only ASCII in Python
This code defines a function that checks whether every character in a given string is an ASCII character (Unicode code point < 128) and demonstrates it with multiple test cases.
def is_ascii_only(text: str) -> bool:
"""Return True if all characters in text are ASCII, False otherwise."""
return all(ord(char) < 128 for char in text)
if __name__ == "__main__":
# Test cases
samples = [
"Hello, world!",
"Café au lait",
"日本語テキスト",
"ASCII only 123",
…
How to Encode and Decode UTF-8 in Python
Convert a Python string to UTF-8 bytes with .encode() and back to text with .decode(), with a simple demo function.
def encode_decode_demo(text: str):
encoded = text.encode("utf-8")
decoded = encoded.decode("utf-8")
print(f"Original string: {text}")
print(f"Encoded bytes: {encoded}")
print(f"Decoded string: {decoded}")
print(f"Match: {text == decoded}")
if __name__ == "__main__":
encode_decode_demo("Hel…
How to Escape HTML in Python
This code demonstrates how to use Python's `html.escape` function to safely encode user input for display in HTML, preventing XSS attacks.
import html
def escape_user_input(user_input: str) -> str:
"""Escape HTML-sensitive characters for safe display."""
return html.escape(user_input)
if __name__ == "__main__":
sample_user_input = '<script>alert("XSS")</script> & \'quotes\''
safe_output = escape_user_input(sample_user_input)
print("…
How to Extract Digits Only from a String in Python
This code uses a regular expression to remove all non-digit characters from a mixed string, returning only the digits.
import re
def extract_digits(text):
"""Return only the digits from the given text as a string."""
return re.sub(r'\D', '', text)
if __name__ == "__main__":
mixed = "abc123def456!@#789"
result = extract_digits(mixed)
print(result)
How to Filter Text to Only Letters, Numbers, and Spaces in Python
A beginner-friendly function that filters a string to keep only alphabetic characters, digits, and spaces, removing punctuation and symbols.
def filter_text(text, keep_alpha=True, keep_digits=True, keep_spaces=True):
allowed = set()
if keep_alpha:
allowed.update("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
if keep_digits:
allowed.update("0123456789")
if keep_spaces:
allowed.add(" ")
return "".join(ch f…
How to Filter a List of Strings by Keyword in Python
A helper function filters a list of strings by a keyword search with optional case sensitivity.
def filter_strings(items, keyword, case_sensitive=False):
"""
Filter a list of strings by a keyword.
Args:
items: list of strings to filter
keyword: substring to search for
case_sensitive: if True, match case exactly
Returns:
list of strings containing the keyw…
How to Format Strings with Named Placeholders in Python
Format a template string using named placeholders with the str.format() method and a dictionary.
def format_named(template, data):
"""Format a template string using named placeholders."""
return template.format(**data)
if __name__ == "__main__":
template = "Hello {name}, you are {age} years old and live in {city}."
data = {"name": "Alice", "age": 30, "city": "London"}
result = format_named(t…
How to Format Text in Python
A beginner-friendly helper that cleans and changes the case of a string, with options for title, upper, lower, and capitalize.
def format_text(text, case="title", strip_whitespace=True, remove_extra_spaces=True):
"""
Formats a string based on common beginner needs.
Args:
text: Input string to format
case: "title", "upper", "lower", or "capitalize"
strip_whitespace: Remove leading/trailing whitespace
…
How to Format Text in Python (Beginner's Guide)
This beginner-friendly Python script demonstrates text formatting basics: stripping whitespace, converting to title case, replacing substrings, splitting into words, and generating a snippet.
text = " hello world, welcome to python skillset! "
cleaned = text.strip()
title_cased = cleaned.title()
replaced = title_cased.replace("Python", "PYTHON")
words = replaced.split()
word_count = len(words)
first_three = " ".join(words[:3])
snippet = first_three + "..."
print("Original:", repr(text))
print("Stripped:"…
How to Format a Float as Currency in Python
This code defines a function that converts a float to a string formatted as US currency with two decimal places and comma separators.
def format_currency(amount):
return f"${amount:,.2f}"
if __name__ == "__main__":
test_amounts = [1234.5, 0, 9999999.999, -42.867]
for amount in test_amounts:
print(f"{amount} -> {format_currency(amount)}")
How to Generate Initials from a Full Name in Python
Extract and uppercase the first letter of each word in a full name to produce initials using standard string methods.
def generate_initials(full_name):
parts = full_name.strip().split()
initials = ''.join(part[0].upper() for part in parts if part)
return initials
if __name__ == "__main__":
name = "john f. kennedy"
print(generate_initials(name))
How to Generate Text Helper Functions in Python
Three simple Python functions that repeat, join, and count characters in strings for beginners.
def repeat_text(text, times):
"""Repeat a string a given number of times."""
return text * times
def join_words(words, separator=" "):
"""Join a list of words into a single string."""
return separator.join(words)
def count_characters(text):
"""Count character occurrences in a string."""
ret…
How to Group Data by Category in Python
Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.
def group_by_category(data):
"""Group list of (category, value) tuples into dictionaries of lists."""
groups = {}
for category, value in data:
groups.setdefault(category, []).append(value)
return groups
if __name__ == "__main__":
items = [
("fruit", "apple"),
("veg", "carro…
How to Highlight Search Terms in Python Text
Highlights all case-insensitive occurrences of a search term in a string by wrapping them in markers.
def highlight_search_term(text: str, term: str) -> str:
"""Highlight all occurrences of term in text using terminal-style markers."""
if not term:
return text
term_lower = term.lower()
result = []
i = 0
while i < len(text):
# Check if the term starts at position i (case-insens…
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.
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()),
…
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.