Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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 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 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 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__":
…
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 Use Template Strings for Substitution in Python
This code shows how to use Python's Template class for safe string substitution, replacing placeholders like $name with actual values.
from string import Template
def format_user_message(name, role, company):
template = Template("Hello $name! We are glad to have you as our $role at $company.")
return template.substitute(name=name, role=role, company=company)
if __name__ == "__main__":
result = format_user_message("Alice", "Python Develo…
How to wrap long text to a specified width in Python
Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.
import textwrap
text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""
wrapped = textwrap.fill(text, width=40)
print(wrapped)
How to Shuffle a List in Python
Shuffle a Python list in place or return a new shuffled copy using the random module.
import random
def shuffle_list(items):
shuffled = items[:]
random.shuffle(shuffled)
return shuffled
if __name__ == "__main__":
original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = shuffle_list(original)
print(f"Original: {original}")
print(f"Shuffled: {result}")
How to Load a .env File Manually in Python
Parse a .env-style key-value file into a Python dictionary using only the standard library, with comment and quoted-value handling.
import re
from pathlib import Path
def load_dotenv_file(filepath: str) -> dict[str, str]:
"""Parse a .env-style file into a dictionary."""
env = {}
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"Environment file not found: {filepath}")
for line in path.read_text()…
How to Parse Command Line Arguments in Python with argparse
Build a CLI that accepts positional integers, an optional --sum flag, and a --verbose switch, all with Python's standard argparse library.
import argparse
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('numbers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
…
How to Emit Deprecation Warnings in Python
Use the warnings module to mark legacy classes and methods as deprecated, letting users know to switch to newer APIs.
import warnings
class OldAPI:
def __init__(self):
warnings.warn(
"OldAPI is deprecated; use NewAPI instead.",
DeprecationWarning,
stacklevel=2,
)
self.data = []
def add(self, item):
warnings.warn(
"OldAPI.add() is deprecated; us…
Implement a Context Manager That Suppresses Exceptions in Python
Shows how to write a custom context manager that catches specified exceptions and optionally re-raises others, plus the stdlib contextlib.suppress alternative.
import contextlib
class SuppressExceptions:
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
return False
if not self.exceptions or exc_type in se…
Log to stderr with Python logging basicConfig
Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.
import logging
def main():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
stream=__import__("sys").stderr,
)
logger = logging.getLogger("example")
logger.debug("Debug message")
logger.info("Info message")
logger.…
Build a File Index by Relative Path Hash Map in Python
Recursively walk a directory and map normalized relative paths to absolute file paths using a defaultdict hash map.
import os
from collections import defaultdict
def build_file_index(root_dir):
index = defaultdict(list)
for dirpath, dirnames, filenames in os.walk(root_dir):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
relative_path = os.path.relpath(full_path, roo…
Compress and Extract ZIP Files Programmatically in Python
Create a ZIP archive with in-memory files and extract its contents to a directory using Python's stdlib zipfile and pathlib modules.
import zipfile
from pathlib import Path
import tempfile
import os
def create_sample_zip(zip_path: str, files: dict) -> None:
"""Create a ZIP file containing the given files (name -> content mapping)."""
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
for filename, content in files.ite…
Convert CSV Files to JSON in Python
Convert a CSV file to a JSON file using Python's built-in csv and json modules.
import csv
import json
def csv_to_json(csv_filepath, json_filepath):
"""Convert a CSV file to a JSON file."""
with open(csv_filepath, mode='r', newline='') as csv_file:
reader = csv.DictReader(csv_file)
data = [row for row in reader]
with open(json_filepath, mode='w') as json_file:
…
Generate Timesheet Reports from Daily Logs in Python
Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.
import json
from pathlib import Path
from collections import defaultdict
def generate_timesheet_report(daily_logs: list[dict]) -> str:
"""
Generate a timesheet report from daily log entries.
Args:
daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
Returns:
…
How to Compress a String to Gzip Bytes in Python
Compress a string into gzip-compressed bytes entirely in memory using the standard library gzip module.
import gzip
def compress_to_gzip_bytes(data: str, encoding: str = "utf-8") -> bytes:
"""Compress a string to gzip-compressed bytes in memory."""
return gzip.compress(data.encode(encoding))
if __name__ == "__main__":
original = "Hello, world! " * 10
compressed = compress_to_gzip_bytes(original)
pr…
How to Decompress a gzip File in Python
This code provides a function to decompress a .gz file, writing the decompressed content to a new file and returning the text, using the gzip standard library module.
import gzip
from pathlib import Path
def decompress_gzip(filepath: str, output_path: str | None = None) -> str:
"""Decompress a .gz file and return the decompressed content."""
input_path = Path(filepath)
if output_path is None:
output_path = str(input_path.with_suffix(""))
with gzip.open…
How to List Tar Archive Contents in Python
Open a tar archive with the stdlib tarfile module and print each entry's type, size, and name.
import tarfile
from pathlib import Path
def list_tar_contents(archive_path):
"""List all entries in a tar archive."""
entries = []
with tarfile.open(archive_path, "r") as tar:
for member in tar.getmembers():
entry_type = "dir" if member.isdir() else "file"
entries.append(f"…
How to Load a YAML Subset in Python Without PyYAML
Parse a flat, key-value YAML file with the Python standard library (re and pathlib), handling comments, quotes, and inline comments while skipping nested structures.
import re
from pathlib import Path
def load_yaml_subset(path):
"""Load a flat YAML file (key: value) without external dependencies."""
data = {}
with open(path, 'r', encoding='utf-8') as f:
for line in f:
# Skip empty lines and comments
line = line.strip()
if no…
How to Parse JSON, TXT, and CSV Files in Python
This code provides simple functions to read and parse JSON, text, and CSV files using Python's standard library, returning native data structures.
import json
from pathlib import Path
def parse_json_file(filepath):
"""Read and parse a JSON file, returning its contents."""
path = Path(filepath)
with path.open('r', encoding='utf-8') as f:
return json.load(f)
def parse_txt_lines(filepath):
"""Read a text file and return non-empty stripped …
How to Parse Path Components with pathlib Path in Python
Parse a file path into parent directory, filename, stem, suffix, and parts using the standard library pathlib module.
from pathlib import Path
if __name__ == "__main__":
p = Path("data/reports/2024/final.txt")
print(f"Path: {p}")
print(f"Parent: {p.parent}")
print(f"Name: {p.name}")
print(f"Stem: {p.stem}")
print(f"Suffix: {p.suffix}")
print(f"Parts: {p.parts}")
print(f"Anchor: {p.anchor}")
print(…
How to Parse XML Attributes into a Flat Dictionary in Python
Parses XML elements and attributes using ElementTree, building a flat dictionary keyed by element attributes.
import xml.etree.ElementTree as ET
xml_data = """<root>
<book id="1" category="fiction" price="9.99">
<title>The Catcher</title>
</book>
<book id="2" category="nonfiction" price="12.50">
<title>Deep Learning</title>
</book>
</root>"""
def parse_xml_attributes(xml_string):
root = E…
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.