Reference library

Python Code Samples

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

55 matches
Strings & text easy

How to Detect Expired Domains Using Python

Parse a list of domain registration data and compare expiry dates to today to find expired domains.

datetime date-parsing domain-check
Python
import datetime

# List of test domains with fake registration and expiry dates
# Format: (domain, registration_date, expiry_date)
test_domains = [
    ('example.com', '2020-01-15', '2024-01-15'),  # Expired
    ('google.com', '1997-09-15', '2026-09-15'),   # Still active
    ('test-site.org', '2019-06-01', '2023-06-0…
50 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}[-…
51 0 Open
Strings & text easy

How to Generate Initials from a Full Name in Python

Extract and uppercase the first letter of each word in a full name to produce initials using standard string methods.

strings initialism text-processing
Python
def generate_initials(full_name):
    parts = full_name.strip().split()
    initials = ''.join(part[0].upper() for part in parts if part)
    return initials

if __name__ == "__main__":
    name = "john f. kennedy"
    print(generate_initials(name))
14 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 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.

string split text parsing delimiter
Python
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…
16 0 Open
Strings & text easy

How to parse key=value pairs in Python

Parse a single line of key=value pairs separated by a delimiter into a Python dictionary.

parsing key-value dictionary
Python
def parse_key_value_pairs(line: str, delimiter: str = "&") -> dict:
    """Parse a single line of key=value pairs into a dictionary."""
    pairs = {}
    for token in line.split(delimiter):
        if not token.strip():
            continue
        key, _, value = token.partition("=")
        pairs[key.strip()] = val…
11 0 Open
Lists & loops easy

How to Parse Bullet Points in Python

Extract bullet point items from raw text by splitting lines and filtering those that start with '- ' or '* '.

text parsing bullet points loops
Python
def parse_bullet_points(text):
    """Extract bullet point items from raw text."""
    lines = text.splitlines()
    items = []
    
    for line in lines:
        stripped = line.strip()
        if stripped.startswith("- ") or stripped.startswith("* "):
            item = stripped[2:]
            if item:
           …
13 0 Open
Lists & loops easy

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.

strings lists loops
Python
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…
15 0 Open
Lists & loops easy

How to Parse a Comma String into a List of Integers in Python

Converts a comma-separated string into a list of integers, handling spaces and empty inputs.

csv parsing list-comprehension
Python
def parse_csv_to_ints(text: str) -> list[int]:
    """Parse a comma-separated string into a list of integers."""
    if not text.strip():
        return []
    return [int(part.strip()) for part in text.split(",") if part.strip()]

if __name__ == "__main__":
    sample = "10, 20, 30, 40, 50"
    result = parse_csv_to_…
13 0 Open
Functions & basics easy

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.

dotenv environment-variables file-parsing
Python
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()…
13 0 Open
Errors & debugging easy

How to Handle ValueError and Multiple Exceptions in Python

This code demonstrates try/except blocks for beginners, handling ZeroDivisionError, TypeError, and ValueError with two practical functions: dividing numbers and parsing strings to floats.

try-except valueerror exception-handling
Python
def divide_numbers(a, b):
    """Divide two numbers with error handling for beginners."""
    try:
        result = a / b
        print(f"{a} / {b} = {result}")
        return result
    except ZeroDivisionError:
        print(f"Error: Cannot divide {a} by zero!")
    except TypeError:
        print(f"Error: Both argu…
13 0 Open
Errors & debugging easy

How to Use try except ValueError in Python to Parse Numbers

Convert strings to integers safely with try/except ValueError and TypeError, returning a value-or-error tuple.

try-except valueerror error-handling
Python
def parse_number(text):
    """Safely convert a string to an integer, handling errors gracefully."""
    try:
        value = int(text)
        return value, None
    except ValueError as error:
        return None, f"Conversion failed: {error}"
    except TypeError as error:
        return None, f"Wrong type provided…
13 0 Open
Errors & debugging easy

Split try except ValueError handler for beginners in Python

Demonstrates how to handle ValueError and ZeroDivisionError separately using try/except blocks, with beginner-friendly examples for parsing and division.

try-except valueerror zerodivisionerror
Python
def parse_number(text):
    try:
        number = int(text)
        return f"Parsed successfully: {number}"
    except ValueError as error:
        return f"Conversion failed: {error}"

def divide_numbers(dividend, divisor):
    try:
        result = dividend / divisor
        return f"Division result: {result}"
    e…
14 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)
       …
17 0 Open
Files & data easy

How to Find HTML Elements by Tag, Class, ID, CSS Selector, and Attribute in BeautifulSoup

Parse an HTML string with BeautifulSoup and demonstrate five distinct ways to locate elements: by tag name, by class, by ID, by CSS selector, and by attribute.

beautifulsoup html parsing
Python
from bs4 import BeautifulSoup

html_content = """
<html><body>
    <h1 id="title" class="heading">Hello World</h1>
    <p class="content">First paragraph</p>
    <p class="content special">Second paragraph</p>
    <a href="https://example.com" class="link">Click here</a>
    <div id="footer">
        <p>© 2024</p>
   …
62 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…
17 0 Open
Files & data easy

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.

json csv file parsing
Python
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 …
14 0 Open
Files & data easy

How to Parse NDJSON Lines into a List in Python

Reads a JSON-lines (NDJSON) file line by line and converts each non-empty line into a Python object, returning a list.

json ndjson file-io
Python
import json
from pathlib import Path


def parse_ndjson(file_path: str) -> list:
    data = []
    with Path(file_path).open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                data.append(json.loads(line))
    return data


if __name__ == "__main__"…
12 0 Open
Files & data easy

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.

xml elementtree parsing
Python
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…
14 0 Open
Files & data easy

How to Read a JSON File into a Dictionary in Python

Load a JSON file into a Python dictionary using the json.load() function with proper file handling and UTF-8 encoding.

json file-io dictionary
Python
import json
from pathlib import Path

def read_json_file(filepath: str) -> dict:
    """Read a JSON file and return its contents as a dictionary."""
    path = Path(filepath)
    with path.open("r", encoding="utf-8") as f:
        data = json.load(f)
    return data

if __name__ == "__main__":
    # Create a sample JS…
13 0 Open
Files & data easy

Parse CSV with Custom Delimiter and Quote Character in Python

Reads a CSV string with a custom delimiter and quote character using the csv module, returning a list of rows.

csv parsing delimiter
Python
import csv
from io import StringIO

def parse_csv(data, delimiter='|', quotechar='"'):
    reader = csv.reader(StringIO(data), delimiter=delimiter, quotechar=quotechar)
    rows = [row for row in reader]
    return rows

if __name__ == "__main__":
    sample = 'Alice|"Smith, Jr."|25\nBob|"Johnson, Sr."|30'
    result …
13 0 Open
Files & data easy

Parse Fixed Width Data File by Column Slices in Python

Extract fields from fixed-width text by slicing each line at defined column offsets, with a dictionary describing the boundaries.

fixed-width string-slicing parsing
Python
from pathlib import Path


def parse_fixed_width(data: str, slices: dict[str, tuple[int, int]]) -> list[dict[str, str]]:
    lines = data.strip().splitlines()
    records = []
    for line in lines:
        record = {}
        for name, (start, end) in slices.items():
            record[name] = line[start:end].strip()…
13 0 Open
Files & data easy

Read a CSV File with csv.DictReader in Python

Read a CSV file as a list of dictionaries, using csv.DictReader to map each row to column names.

csv csv-dictreader file-reading
Python
import csv
from pathlib import Path

def read_csv_with_dictreader(file_path):
    data = []
    with open(file_path, mode='r', newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            data.append(row)
    return data

if __name__ == "__main__":
    # Cre…
10 0 Open
Files & data easy

Read an XML File with xml.etree.ElementTree in Python

Parse an XML file and print its root and child elements using the standard library's xml.etree.ElementTree module.

xml elementtree file-io
Python
import xml.etree.ElementTree as ET


def read_xml_file(file_path):
    """Read an XML file and print its structure."""
    tree = ET.parse(file_path)
    root = tree.getroot()
    print(f"Root element: {root.tag}")
    for child in root:
        print(f"Child element: {child.tag}, text: {child.text}")


if __name__ ==…
12 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.