Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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 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 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 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 Normalize Text in Python
This code defines a function that trims, lowercases, and collapses extra whitespace in a string, returning normalized text.
def normalize_text(text: str) -> str:
normalized = " ".join(text.lower().strip().split())
return normalized
if __name__ == "__main__":
raw = " Hello, WORLD! This is a test. "
print(normalize_text(raw))
How to Parse and Clean Text in Python
This code defines three helper functions to parse text into lowercase words, count unique word frequencies, and clean text by removing punctuation and extra whitespace.
def extract_words(text: str) -> list[str]:
"""Return a list of lowercase words from the given text."""
return [word.lower() for word in text.split() if word.isalpha()]
def count_unique_words(text: str) -> dict[str, int]:
"""Return a dictionary with unique words and their frequencies."""
words = extra…
How to Remove Duplicate Adjacent Spaces in Python
This Python function collapses any sequence of two or more adjacent spaces into a single space, preserving all other characters.
def remove_duplicate_adjacent_spaces(text):
"""Replace sequences of 2+ spaces with a single space."""
result = []
prev_was_space = False
for char in text:
if char == " ":
if not prev_was_space:
result.append(char)
prev_was_space = True
else:
…
How to Remove HTML Tags in Python with Regex
Strips all HTML tags from a string using a regular expression and cleans extra whitespace.
import re
def remove_html_tags(text: str) -> str:
"""Remove all HTML tags from the given text using regex."""
# Remove opening and closing tags
clean = re.sub(r'<[^>]+>', '', text)
# Remove any extra whitespace left behind
clean = re.sub(r'\s+', ' ', clean).strip()
return clean
if __name__ ==…
How to Replace Multiple Spaces with a Single Space in Python
This snippet uses the `re` module to collapse runs of consecutive spaces in a string into a single space, cleaning up whitespace.
import re
def collapse_spaces(text):
"""Replace multiple consecutive spaces with a single space."""
return re.sub(r' +', ' ', text)
if __name__ == "__main__":
sample = "This has multiple spaces between words."
result = collapse_spaces(sample)
print(f"Original: '{sample}'")
print(f"Co…
How to Round Numbers with f-strings in Python
Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.
def main():
# Values to format with expression-based rounding
price = 19.995
tax_rate = 0.0825
distance = 1234.56789
# Round inside the f-string expression using round()
print(f"Price rounded to cents: ${round(price, 2)}")
# Combine rounding with arithmetic inside the expression
total…
How to Split Strings in Python (Beginner-Friendly)
Split Python strings by a delimiter into lists, plus a cleanup variant that strips whitespace and filters empty parts.
def split_text(text, delimiter=" "):
"""Split a string by a delimiter and return a list of parts."""
return text.split(delimiter)
def split_text_with_cleanup(text, delimiter=" "):
"""Split a string, stripping whitespace and filtering empty parts."""
parts = text.split(delimiter)
cleaned = [part.s…
How to Strip Whitespace in Python
This code demonstrates how to remove leading and trailing whitespace from a string using the built-in strip() method.
def strip_whitespace(text: str) -> str:
return text.strip()
if __name__ == "__main__":
sample = " Hello, world! "
result = strip_whitespace(sample)
print(f"Original: '{sample}'")
print(f"Stripped: '{result}'")
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 remove punctuation from a string in Python
Remove all punctuation characters from a string using the str.translate method and string.punctuation from the standard library.
import string
def remove_punctuation(text: str) -> str:
return text.translate(str.maketrans("", "", string.punctuation))
if __name__ == "__main__":
sample = "Hello, world! It's a test... (with punctuation) - done?"
cleaned = remove_punctuation(sample)
print(f"Original: {sample}")
print(f"Cleaned:…
How to Filter None Values from a Mixed List in Python
Filter None values from a mixed Python list using a list comprehension with the `is not None` condition.
mixed_list = [1, None, "hello", None, 3.14, None, [1, 2], None]
filtered_list = [item for item in mixed_list if item is not None]
print(f"Original list: {mixed_list}")
print(f"Filtered list: {filtered_list}")
print(f"Original length: {len(mixed_list)}, Filtered length: {len(filtered_list)}")
How to Parse Delimited Data into a Python List
Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.
def parse_data(raw_data):
"""Parse a pipe-delimited string into a list of cleaned items."""
items = raw_data.split("|")
parsed = []
for item in items:
cleaned = item.strip()
if cleaned:
parsed.append(cleaned)
return parsed
if __name__ == "__main__":
data = " apple…
Replace Negative Values in a List with Python
This code defines a function that replaces every negative number in a list with a replacement value, defaulting to zero, using a list comprehension.
def replace_if_negative(values, replacement=0):
return [replacement if value < 0 else value for value in values]
if __name__ == "__main__":
numbers = [5, -3, 8, -1, 0, -7, 2]
result = replace_if_negative(numbers)
print(f"Original: {numbers}")
print(f"Replaced: {result}")
How to define an exception hierarchy for domain errors in Python
Create a custom exception hierarchy with a base DomainError class and specific subclasses to handle validation, not-found, permission, and concurrency errors cleanly in Python apps.
class DomainError(Exception):
"""Base class for all domain errors."""
pass
class ValidationError(DomainError):
"""Raised when input data fails validation rules."""
pass
class NotFoundError(DomainError):
"""Raised when a requested entity does not exist."""
pass
class PermissionDeniedError(Dom…
Automatically Highlight Data Validation Errors Inside Excel Files in Python
Load an Excel file with openpyxl, iterate over cells, and highlight invalid data (empty, negative) with a red fill and error message.
import openpyxl
from openpyxl.styles import PatternFill
from pathlib import Path
def highlight_validation_errors(filepath: str, output_path: str = None):
wb = openpyxl.load_workbook(filepath)
red_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid")
for sheet in wb.worksheet…
Build a Python Script That Detects and Deletes Empty Files Across Folders
A Python script that recursively finds and removes all zero-byte files across nested directories, returning a list of deleted paths.
import os
from pathlib import Path
def find_and_delete_empty_files(root_dir: str) -> list:
"""Find and delete all empty files under root_dir. Returns list of deleted paths."""
deleted = []
for file_path in Path(root_dir).rglob('*'):
if file_path.is_file() and file_path.stat().st_size == 0:
…
Detect Outliers in CSV Data Using Z-Score in Python
Read a CSV file and detect outliers in a numeric column by computing z-scores, flagging those exceeding a given threshold — no machine learning required.
import csv
import statistics
from math import sqrt
def detect_outliers(csv_path, column_name, threshold=2.0):
"""Detect outliers in a numeric column using z-score method."""
values = []
with open(csv_path, 'r', newline='') as f:
reader = csv.DictReader(f)
if column_name not in reader.field…
How to Convert CSV Column Types While Reading in Python
Read a CSV file and automatically convert column values to int, float, str, or bool based on type suffixes in the header names.
import csv
from pathlib import Path
from typing import Any
def read_csv_with_types(filepath: str) -> list[dict[str, Any]]:
"""Read CSV and convert column types based on header suffixes."""
converters = {
"int": int,
"float": float,
"str": str,
"bool": lambda v: v.strip().lower(…
How to Handle Missing Values in a CSV Numeric Column in Python
Clean missing entries in a CSV numeric column by filling them with the mean, median, a custom value, or dropping rows.
import csv
from pathlib import Path
import statistics
def clean_csv_numeric(input_path: str, output_path: str, column: str, strategy: str = "mean") -> None:
"""
Handles missing values in a numeric column of a CSV file.
Strategies: 'mean', 'median', 'drop', or 'fill' with a specified value.
"""
row…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.