Reference library

Python Code Samples

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

10 matches
Strings & text easy

How to Encode and Decode UTF-8 in Python

Convert a Python string to UTF-8 bytes with .encode() and back to text with .decode(), with a simple demo function.

utf-8 encode decode
Python
def encode_decode_demo(text: str):
    encoded = text.encode("utf-8")
    decoded = encoded.decode("utf-8")
    print(f"Original string: {text}")
    print(f"Encoded bytes: {encoded}")
    print(f"Decoded string: {decoded}")
    print(f"Match: {text == decoded}")

if __name__ == "__main__":
    encode_decode_demo("Hel…
14 0 Open
Errors & debugging easy

How to Validate JSON in Python and Catch JSONDecodeError

A robust Python function that attempts to parse JSON strings and returns a boolean plus either the parsed data or a descriptive error message when decoding fails.

json validation jsondecodeerror
Python
import json

def validate_json(json_string):
    """Try to parse JSON, return (is_valid, data_or_error)."""
    try:
        data = json.loads(json_string)
        return True, data
    except json.JSONDecodeError as e:
        return False, f"Invalid JSON: {e}"

if __name__ == "__main__":
    test_inputs = [
        …
11 0 Open
Files & data easy

How to Detect File Encoding: UTF-8 vs Latin-1 in Python

Detect whether a file is UTF-8 or Latin-1 encoded by attempting a UTF-8 decode and falling back to Latin-1.

file-encoding utf-8 latin-1
Python
import sys

def detect_encoding(file_path):
    with open(file_path, 'rb') as f:
        raw = f.read()
    
    try:
        raw.decode('utf-8')
        return 'UTF-8'
    except UnicodeDecodeError:
        return 'latin1'

if __name__ == "__main__":
    file_path = sys.argv[1] if len(sys.argv) > 1 else 'sample.txt'
…
13 0 Open
Algorithms & data structures medium

How to Decode a String with Repeated Brackets in Python

Decodes strings with patterns like '3[a]2[bc]' by using a stack to handle nested and repeated bracket groups.

stack string-decoding algorithms
Python
def decode_string(s: str) -> str:
    stack = []
    current_num = 0
    current_str = ""

    for ch in s:
        if ch.isdigit():
            current_num = current_num * 10 + int(ch)
        elif ch == "[":
            stack.append((current_str, current_num))
            current_str = ""
            current_num = 0…
13 0 Open
Comprehensions & generators medium

How to stream parse JSON arrays in Python

This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.

json generator streaming
Python
import json


def json_array_stream(items):
    """Generator that yields JSON-encoded values one at a time."""
    yield "["
    for i, item in enumerate(items):
        if i > 0:
            yield ","
        yield json.dumps(item)
    yield "]"


def parse_json_stream(stream):
    """Consumes a stream of JSON fragme…
14 0 Open
API design & gRPC easy

How to Decode Basic Auth Credentials in Python

Decode username and password from a Basic Auth header string using base64 and standard string operations.

base64 authentication api
Python
import base64

def decode_basic_auth(header_value):
    """
    Decode credentials from a Basic Auth header value.
    
    Expected format: "Basic base64encoded(username:password)"
    Returns a tuple (username, password).
    """
    if not header_value.startswith("Basic "):
        raise ValueError("Invalid Basic A…
13 0 Open
API design & gRPC easy

How to Validate JWT Claims (exp, iss, aud) in Python

This code demonstrates how to decode and validate a JWT's essential claims—expiration (exp), issuer (iss), and audience (aud)—using the PyJWT library, returning clear error messages for common validation failures.

jwt authentication security
Python
import jwt
from datetime import datetime, timezone, timedelta

SECRET = "mock-secret"

def validate_token(token, expected_iss, expected_aud):
    try:
        decoded = jwt.decode(
            token,
            SECRET,
            algorithms=["HS256"],
            options={"require": ["exp", "iss", "aud"]},
         …
12 0 Open
Streaming & messaging medium

How to Encode and Decode Avro Data in Python (Roundtrip)

Serialize a Python dict to Avro binary bytes and decode it back using the fastavro-compatible avro library.

avro serialization encode
Python
import io
import json
from avro.schema import parse
from avro.io import DatumWriter, DatumReader, BinaryEncoder, BinaryDecoder

def avro_roundtrip(schema_json, data):
    schema = parse(json.dumps(schema_json))
    bytes_writer = io.BytesIO()
    encoder = BinaryEncoder(bytes_writer)
    writer = DatumWriter(schema)
 …
14 0 Open
Auth & security at scale medium

How to Encode and Decode JWT with HS256 in Python

Implement JWT encoding and decoding using HMAC-SHA256 (HS256) with Python's standard library, including signature verification.

jwt hmac authentication
Python
import base64
import hashlib
import hmac
import json


def base64url_encode(data: bytes) -> bytes:
    return base64.urlsafe_b64encode(data).rstrip(b"=")


def base64url_decode(data: str) -> bytes:
    padding = "=" * (-len(data) % 4)
    return base64.urlsafe_b64decode(data + padding)


def encode_jwt(payload: dict, …
16 0 Open
Auth & security at scale medium

How to sign and verify JWT RS256 in Python

Generate RSA keys, create a JWT signed with RS256, verify its signature, and decode the payload using the cryptography library.

jwt rs256 rsa
Python
import json
import time
import base64
import hmac
import hashlib
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.utils import encode_ds…
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.