Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

8 matches
Strings & text easy

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.

string translation character-mapping
Python
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…
11 0 Open
Files & data medium

Scrape HTML Tables and Convert Them to CSV Using Beautiful Soup in Python

Scrape a Wikipedia table with Beautiful Soup and write the data to a CSV file using the csv module.

web scraping beautiful soup csv
Python
import requests
from bs4 import BeautifulSoup
import csv

url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

tables = soup.find_all('table', {'class': 'wikitable'})

if tables:
    target_table = tables[2]
    rows =…
47 0 Open
Automation & scripting medium

Convert HTML Tables to Excel Reports in Python

Convert HTML tables into formatted Excel reports using BeautifulSoup and Pandas with auto-adjusted column widths.

html excel beautifulsoup
Python
import pandas as pd
from bs4 import BeautifulSoup
from pathlib import Path

def html_table_to_excel(html_file: str, excel_file: str) -> None:
    """Convert HTML table to formatted Excel report."""
    with open(html_file, 'r', encoding='utf-8') as f:
        html_content = f.read()
    
    soup = BeautifulSoup(html_…
45 0 Open
Automation & scripting medium

Scrape HTML Tables in Python with html.parser

Extract data from HTML tables using Python's built-in html.parser module, without third-party dependencies, by overriding callback methods to track table, row, and cell states.

html scraping parser
Python
import html.parser
from urllib.request import urlopen


class TableParser(html.parser.HTMLParser):
    def __init__(self):
        super().__init__()
        self.in_table = False
        self.in_row = False
        self.in_cell = False
        self.current_cell = []
        self.rows = []
        self.row = []

    d…
12 0 Open
Data pipelines & processing medium

How to perform a star schema join in Python

Denormalize mock fact and dimension tables by building lookup dicts and enriching each sales fact with customer, product, and date attributes.

star-schema data-joins dimensional-modeling
Python
from datetime import date

# Mock dimension tables
customers = [
    {"customer_id": 1, "name": "Alice", "city": "New York"},
    {"customer_id": 2, "name": "Bob", "city": "Los Angeles"},
    {"customer_id": 3, "name": "Carol", "city": "Chicago"},
]

products = [
    {"product_id": 101, "name": "Laptop", "category": "…
12 0 Open
Big data & Spark easy

How to Mock a Hash Join on Large and Small Tables in Python

This code efficiently joins a large dataset (1000 rows) with a small lookup table (20 rows) by building a dictionary hash lookup, mimicking a hash join strategy used in big data systems.

hash-join dictionaries data-join
Python
import random
from pprint import pprint

# Large table: 1000 rows (id, group_id, value)
large = [{"id": i, "group_id": random.randint(1, 20), "value": random.random() * 100} for i in range(1000)]

# Small table: 20 rows (group_id, label)
small = [{"group_id": g, "label": f"Group-{g}"} for g in range(1, 21)]

# Mock a …
13 0 Open
Database scaling & optimization medium

How to Explain SQLite Query Plans in Python

Build a Python function that runs EXPLAIN QUERY PLAN on SQLite in-memory tables and prints the optimizer's execution plan for any SELECT statement.

sqlite query-plan optimization
Python
import sqlite3

def explain_query(sql: str) -> str:
    """Return the SQLite query plan for the given SQL statement."""
    conn = sqlite3.connect(":memory:")
    cursor = conn.cursor()
    
    # Create sample data for a realistic plan
    cursor.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
    c…
14 0 Open
Database scaling & optimization easy

Monitor Database Index Bloat in Python

Simulates index bloat checks for database tables using random ratio thresholds and reports alerts per index.

database index monitoring
Python
import random
import time

class IndexBloatMonitor:
    def __init__(self, thresholds=(0.5, 0.8, 0.9)):
        self.thresholds = thresholds
        self.indices = {
            "users_pk": 48.2,
            "orders_created_idx": 124.7,
            "products_name_idx": 15.3,
            "payments_user_idx": 203.9,
   …
15 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.