Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

16 matches
Strings & text medium

Convert Natural Language Dates to Datetime in Python

Parse common natural language date phrases like 'tomorrow' or 'in 3 days' into Python datetime objects using regex and timedelta.

datetime natural-language regex
Python
from datetime import datetime, timedelta
import re

def parse_natural_date(text: str) -> datetime:
    """Convert common natural language date expressions to datetime objects."""
    now = datetime.now()
    text = text.lower().strip()
    
    # Handle relative dates
    patterns = {
        r"today": now,
        r"…
61 0 Open
Errors & debugging medium

Redact secrets from log message formatter in Python

Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.

logging redaction security
Python
import re
import logging

class RedactingFormatter(logging.Formatter):
    """Formatter that masks sensitive data in log messages."""
    
    SENSITIVE_PATTERNS = [
        (re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
        (re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
14 0 Open
Files & data medium

How to Parse Apache Log Files in Python

Parse Apache common log format lines into structured dictionaries using Python's standard library.

apache regex log-parsing
Python
import re
from pathlib import Path

def parse_apache_line(line):
    pattern = r'^(\S+) (\S+) (\S+) \[([^\]]+)\] "(\S+) (\S+) (\S+)" (\d{3}) (\S+)'
    match = re.match(pattern, line)
    if not match:
        return None
    ip, ident, user, timestamp, method, path, protocol, status, size = match.groups()
    return …
15 0 Open
Algorithms & data structures medium

How to Detect Hardcoded Secrets in Python Source Code

A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.

secrets regex security
Python
import re

def detect_secrets(text):
    """Detect potential hardcoded secrets in source code."""
    patterns = {
        'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
        'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
        'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
42 0 Open
AI & LLM integration patterns medium

How to Detect Prompt Injection in Python

Implements a regex-based heuristic in Python to flag common prompt injection attempts before sending input to an LLM.

prompt-injection regex llm-security
Python
import re

def contains_prompt_injection(user_input: str) -> bool:
    # Directives to ignore previous instructions or act as system
    ignore_patterns = [
        r"\bignore\s+(all\s+)?previous\s+instructions\b",
        r"\bdisregard\s+(all\s+)?previous\s+instructions\b",
        r"\bdon'?t\s+follow\s+(any\s+)?inst…
13 0 Open
AI & LLM integration patterns medium

Parse ReAct Logs into Thought Action Observation Steps in Python

Parse a ReAct agent's textual log into structured steps with thought, action, and observation using regex and named tuples.

react regex llm
Python
import re
from collections import namedtuple


ReActStep = namedtuple("ReActStep", ["thought", "action", "observation"])


def parse_react_log(log: str) -> list[ReActStep]:
    """Parse a ReAct log into structured thought/action/observation steps."""
    pattern = re.compile(
        r"Thought:\s*(?P<thought>.+?)\s*"
…
13 0 Open
Automation & scripting medium

Build a Python Tool to Find All API Endpoints on a Website

A Python script that crawls a website, searches for common API endpoint patterns in HTML and JavaScript, and returns all discovered public API URLs.

api web-crawling automation
Python
import re
import requests
from urllib.parse import urljoin, urlparse
from collections import deque

def find_api_endpoints(base_url, max_pages=10):
    visited = set()
    queue = deque([base_url])
    api_endpoints = set()
    
    api_patterns = [
        r'/api/[a-zA-Z0-9_/-]+',
        r'/v[0-9]+/[a-zA-Z0-9_/-]+',…
52 0 Open
Automation & scripting medium

Convert DOCX to Text by Unzipping XML in Python

Extract plain text from a .docx file by unzipping the container and parsing word/document.xml with regex, using only Python's standard library.

docx zipfile xml
Python
import zipfile
import re
from pathlib import Path

def docx_to_text_unzip_xml(docx_path: str) -> str:
    """Extract plain text from a .docx file by unzipping and parsing document.xml."""
    docx_path = Path(docx_path)
    if not docx_path.exists():
        raise FileNotFoundError(f"File not found: {docx_path}")

   …
11 0 Open
Automation & scripting medium

Discover RSS Feeds From Any Website in Python

Scrape a website's HTML to automatically find all linked RSS or Atom feed URLs using requests, BeautifulSoup, and regex.

rss web-scraping beautifulsoup
Python
import requests
import re
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup

def discover_rss_feeds(url):
    """Discover all RSS/Atom feeds linked from a given website."""
    try:
        headers = {'User-Agent': 'Mozilla/5.0 (compatible; RSSDiscovery/1.0)'}
        response = requests.get(url…
42 0 Open
Automation & scripting medium

Extract All Links from Any Website in Python

Scrape a webpage and extract all absolute HTTP/HTTPS links using requests and regex.

web-scraping links requests
Python
import requests
import re
from urllib.parse import urljoin

def extract_links(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        html = response.text
        # Find all href attributes in anchor tags
        pattern = r'href=["\'](.*?)["\']'
        raw_links = re.findall(p…
42 0 Open
Automation & scripting medium

Find Sensitive Information in Log Files with Python

Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in Python.

regex security log-analysis
Python
import re
import os
from pathlib import Path

def find_sensitive_info(log_path):
    """Scans log files for patterns like emails, IPs, API keys, and passwords."""
    patterns = {
        'Email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
        'IP Address': r'\b(?:\d{1,3}\.){3}\d{1,3}\b',
        'API Key'…
36 0 Open
Automation & scripting medium

How to Detect Unused Images in a Project with Python

A Python script that scans a website project folder, identifies all image files, and checks HTML/CSS/JS files to find which images are never referenced.

automation files regex
Python
import os
import re
from pathlib import Path

def find_unused_images(project_path):
    image_exts = {'.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp'}
    used_images = set()
    all_images = set()
    
    # Find all image files
    for root, _, files in os.walk(project_path):
        for file in files:
            …
38 0 Open
Automation & scripting medium

How to Scan Configuration Files for Security Issues in Python

Automatically scan configuration files for common security mistakes using regex rules in Python.

security config regex
Python
import re
import os
from pathlib import Path

SECURITY_RULES = [
    (r'^#\s*INSECURE_', 'Insecure comment starts with # INSECURE_'),
    (r'password\s*=\s*("|\\\')?[^"\\\'"\s]+("|\\\')?$', 'Hardcoded password'),
    (r'debug\s*=\s*True', 'Debug mode enabled'),
    (r'[Pp]ermit[Rr]ootLogin\s+yes', 'PermitRootLogin ena…
48 0 Open
Git + Python medium

How to Make a Git Commit Heatmap by Hour in Python

Parse a git log output and count commits by weekday and hour, then print a compact heatmap table.

git logging datetime
Python
import re
from collections import Counter
from datetime import datetime

def parse_commits(log_text):
    """Parse git log lines and count commits by (weekday, hour)."""
    pattern = re.compile(r"^Date:\s+(.+)$")
    counts = Counter()
    
    for line in log_text.splitlines():
        match = pattern.match(line)
  …
13 0 Open
Git + Python medium

Python Script to Rotate a Leaked API Key

A checklist-driven Python script that scans a codebase for a leaked API key, replaces it with a new one, and prints a step-by-step rotation checklist.

security secrets file-scanning
Python
#!/usr/bin/env python3
"""Checklist for rotating a leaked API key across a codebase."""

import re
from pathlib import Path


CHECKLIST = [
    "Identify all files containing the leaked key",
    "Generate a new key with sufficient entropy",
    "Update the secret storage/CI environment variables",
    "Replace the ol…
14 0 Open
Big data & Spark medium

How to Implement a Mock MapReduce for Word Count in Python

Simulates a MapReduce word count pipeline with mapper, shuffle, and reducer phases using Python dicts and standard library modules.

mapreduce word-count big-data
Python
from collections import defaultdict
import re

def mapper(text):
    """Split text into words and emit (word, 1) pairs."""
    words = re.findall(r'\b\w+\b', text.lower())
    return [(word, 1) for word in words]

def reducer(pairs):
    """Group word-count pairs and sum counts."""
    counts = defaultdict(int)
    fo…
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.