Reference library

Python Code Samples

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

49 matches
Strings & text easy

Build a Secure Password Strength Checker in Python

A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.

password security regex
Python
import re

def password_strength(password: str) -> str:
    score = 0
    if len(password) >= 8:
        score += 1
    if re.search(r'[a-z]', password):
        score += 1
    if re.search(r'[A-Z]', password):
        score += 1
    if re.search(r'\d', password):
        score += 1
    if re.search(r'[!@#$%^&*(),.?":…
54 0 Open
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"…
60 0 Open
Strings & text easy

Extract Email-Like Tokens from Text in Python

Uses a regular expression to find all email-like tokens in a string, returning them as a list with re.findall.

regex email findall
Python
import re

def extract_email_like_tokens(text):
    pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'
    return re.findall(pattern, text)

if __name__ == "__main__":
    sample_text = (
        "Contact us at support@example.com or sales@company.co.uk. "
        "Invalid: hello@world, user@.com, test@do…
17 0 Open
Strings & text easy

Extract URLs from text with regex in Python

Uses a regular expression to find and print HTTP/HTTPS URLs from a block of text.

regex url text-processing
Python
import re

text = """
Visit https://www.example.com for docs.
Contact support@mysite.org.
Check http://localhost:8000/api or ftp://files.example.net.
"""

url_pattern = r'https?://[^\s]+'

urls = re.findall(url_pattern, text)

for url in urls:
    print(url)
14 0 Open
Strings & text easy

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.

strings camelcase snakecase
Python
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…
10 0 Open
Strings & text easy

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.

pii regex data-privacy
Python
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}[-…
50 0 Open
Strings & text easy

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.

regex string manipulation data cleaning
Python
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)
11 0 Open
Strings & text easy

How to Mask Credit Card Middle Digits in Python

Mask the middle digits of credit card numbers in a string, keeping only the first 8 and last 4 digits, using regular expressions.

regex string-manipulation security
Python
import re

def mask_credit_card(text: str) -> str:
    pattern = re.compile(r'(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4})')
    return pattern.sub(lambda m: m.group(1) + m.group(2) + '****' + m.group(4), text)

if __name__ == "__main__":
    sample = "Card: 1234-5678-9012-3456 and 1111 2222 3333 4444"
    print(mas…
12 0 Open
Strings & text easy

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.

text parsing string cleaning word frequency
Python
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…
11 0 Open
Strings & text easy

How to Remove HTML Tags in Python with Regex

Strips all HTML tags from a string using a regular expression and cleans extra whitespace.

regex html text-cleaning
Python
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__ ==…
12 0 Open
Strings & text easy

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.

regex strings whitespace
Python
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…
14 0 Open
Strings & text easy

Reverse Words in a Sentence While Keeping Punctuation in Python

Reverses the order of words in a sentence while leaving punctuation and spaces in their original positions using Python's re module.

strings punctuation regex
Python
def reverse_words_preserving_punctuation(sentence: str) -> str:
    import re
    # Split into words and punctuation tokens
    tokens = re.findall(r'\w+|[^\w\s]|\s+', sentence)
    words = [t for t in tokens if re.fullmatch(r'\w+', t)]
    words.reverse()
    result_parts = []
    word_index = 0
    for token in toke…
12 0 Open
Strings & text easy

Validate email format with regex in Python

A Python function using a regex pattern to validate simple email formats, returning True or False for each input.

regex email validation
Python
import re

def is_valid_email(email):
    pattern = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'
    return bool(re.match(pattern, email))

if __name__ == "__main__":
    test_emails = [
        "user@example.com",
        "first.last@sub.domain.org",
        "invalid-email",
        "user@.com",
        "user@…
11 0 Open
Errors & debugging easy

How to Validate an Email Address and Raise ValueError in Python

This code defines a validate_email function that checks an email address against a regex pattern and several rules, raising ValueError with a specific reason when invalid.

validation regex errors
Python
import re

def validate_email(email: str) -> str:
    """Validate an email address and return it if valid, otherwise raise ValueError."""
    if not isinstance(email, str):
        raise ValueError("Email must be a string")
    if len(email) > 254:
        raise ValueError("Email length exceeds 254 characters")

    #…
13 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…
13 0 Open
Files & data easy

How to Extract IP Address Counts from Access Logs in Python

Read a web server access log, count occurrences of each IP address using regex and Counter, and print the ranked results.

regex access log counter
Python
import re
from collections import Counter
from pathlib import Path

def extract_ip_counts(log_file_path):
    ip_pattern = r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
    ip_counter = Counter()
    
    with open(log_file_path, 'r') as file:
        for line in file:
            match = re.match(ip_pattern, line)
       …
16 0 Open
Files & data easy

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.

yaml parsing stdlib
Python
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…
16 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 …
14 0 Open
Files & data easy

How to Sanitize Filenames in Python

Strip illegal filename characters and clean up names for safe filesystem use.

filenames sanitize re
Python
import re
from pathlib import Path

def sanitize_filename(filename: str, replacement: str = "_") -> str:
    """
    Remove illegal characters from a filename.
    
    Illegal characters: / \\ : * ? " < > |
    Also strips leading/trailing spaces and dots.
    """
    # Remove illegal characters
    sanitized = re.su…
11 0 Open
Files & data easy

Normalize CSV Column Names to snake_case in Python

Convert CSV header names to snake_case using a regular expression and write the updated file in place.

csv regex snake-case
Python
import csv
import re
import sys


def to_snake_case(header):
    header = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", header)
    header = re.sub(r"[^a-zA-Z0-9]+", "_", header).strip("_").lower()
    return header


def normalize_csv_headers(input_path, output_path=None):
    with open(input_path, newline="", encoding="utf…
12 0 Open
Dictionaries & sets easy

Count Word Frequency in Python with dict

Count how often each word appears in a text using Python's collections.Counter and regular expressions.

dictionary counter frequency
Python
from collections import Counter
import re

def count_word_frequency(text):
    """Count frequency of each word in text (case-insensitive)."""
    words = re.findall(r"\b\w+\b", text.lower())
    return dict(Counter(words))

if __name__ == "__main__":
    sample_text = "The quick brown fox jumps over the lazy dog. The …
12 0 Open
Dictionaries & sets easy

Count word frequency in Python with dict and Counter

Count how often each word appears in a string using Counter, converted to a plain dict, and print results alphabetically.

counter dictionary word-frequency
Python
from collections import Counter
import re

def count_word_frequency(text):
    words = re.findall(r'\b\w+\b', text.lower())
    return dict(Counter(words))

if __name__ == "__main__":
    sample_text = "The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs."
    frequency = count_word_frequency(…
11 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

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.