Reference library

Python Code Samples

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

21 matches
Strings & text easy

How to Align Text in Two Columns with ljust in Python

Format pairs of strings into two aligned columns using ljust padding.

string-formatting ljust alignment
Python
items = [
    ("apple", "red"),
    ("banana", "yellow"),
    ("cherry", "dark red"),
    ("date", "brown")
]

col1_width = max(len(name) for name, _ in items) + 2

for name, color in items:
    print(name.ljust(col1_width) + color)
15 0 Open
Strings & text easy

How to Center Text in a Fixed-Width Banner in Python

Centers any text inside a fixed-width banner using fill characters and computed padding.

strings formatting text-alignment
Python
def center_text_banner(text, width=40, fill_char="="):
    """Center text within a fixed-width banner."""
    if len(text) >= width:
        return text
    
    total_padding = width - len(text)
    left_padding = total_padding // 2
    right_padding = total_padding - left_padding
    
    banner_line = fill_char * w…
14 0 Open
Strings & text easy

How to Convert snake_case to Title Case in Python

Convert snake_case strings to title case by splitting on underscores, capitalizing each word, and joining them with spaces.

snake-case string-formatting text-processing
Python
def to_title_case(snake_str):
    words = snake_str.split("_")
    return " ".join(word.capitalize() for word in words)

if __name__ == "__main__":
    examples = ["hello_world", "convert_snake_case", "already_title_case", "multiple__under_scores"]
    for example in examples:
        print(f"{example!r:35} -> {to_tit…
12 0 Open
Strings & text easy

How to Format Text in Python

A beginner-friendly helper that cleans and changes the case of a string, with options for title, upper, lower, and capitalize.

string formatting case
Python
def format_text(text, case="title", strip_whitespace=True, remove_extra_spaces=True):
    """
    Formats a string based on common beginner needs.
    
    Args:
        text: Input string to format
        case: "title", "upper", "lower", or "capitalize"
        strip_whitespace: Remove leading/trailing whitespace
  …
12 0 Open
Strings & text easy

How to Format Text in Python (Beginner's Guide)

This beginner-friendly Python script demonstrates text formatting basics: stripping whitespace, converting to title case, replacing substrings, splitting into words, and generating a snippet.

string-manipulation text-formatting beginner
Python
text = "  hello world, welcome to python skillset!  "
cleaned = text.strip()
title_cased = cleaned.title()
replaced = title_cased.replace("Python", "PYTHON")
words = replaced.split()
word_count = len(words)
first_three = " ".join(words[:3])
snippet = first_three + "..."
print("Original:", repr(text))
print("Stripped:"…
13 0 Open
Strings & text easy

How to Format a Float as Currency in Python

This code defines a function that converts a float to a string formatted as US currency with two decimal places and comma separators.

formatting currency f-string
Python
def format_currency(amount):
    return f"${amount:,.2f}"

if __name__ == "__main__":
    test_amounts = [1234.5, 0, 9999999.999, -42.867]
    for amount in test_amounts:
        print(f"{amount} -> {format_currency(amount)}")
13 0 Open
Strings & text easy

How to Pad a String with Zeros in Python

Pad a string to a fixed width by left-filling it with zeros using the built-in str.zfill method.

strings padding zfill
Python
def pad_zeros(s, width):
    return s.zfill(width)

if __name__ == "__main__":
    print(repr(pad_zeros("42", 6)))
    print(repr(pad_zeros("-7", 5)))
    print(repr(pad_zeros("hello", 10)))
    print(repr(pad_zeros("123", 3)))
16 0 Open
Strings & text easy

How to Round Numbers with f-strings in Python

Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.

f-string rounding formatting
Python
def main():
    # Values to format with expression-based rounding
    price = 19.995
    tax_rate = 0.0825
    distance = 1234.56789

    # Round inside the f-string expression using round()
    print(f"Price rounded to cents: ${round(price, 2)}")

    # Combine rounding with arithmetic inside the expression
    total…
12 0 Open
Strings & text easy

How to wrap long text to a specified width in Python

Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.

textwrap text wrapping formatting
Python
import textwrap

text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""

wrapped = textwrap.fill(text, width=40)

print(wrapped)
11 0 Open
Lists & loops easy

Format Lists of Tuples into Numbered Lines in Python

This code loops through a list of (name, grade) tuples and formats each into a numbered line using enumerate and f-strings.

enumerate formatting lists
Python
def format_students(students):
    formatted = []
    for i, student in enumerate(students, start=1):
        name, grade = student
        formatted.append(f"{i}. {name}: {grade}")
    return "\n".join(formatted)


if __name__ == "__main__":
    students = [
        ("Alice", 92),
        ("Bob", 85),
        ("Charl…
15 0 Open
Functions & basics easy

Format CLI help text in Python

Build a readable usage string for a command-line tool, aligning flags and wrapping descriptions with the textwrap module.

cli textwrap formatting
Python
import textwrap


def format_help(command_name: str, description: str, options: list[tuple[str, str]]) -> str:
    """Format CLI help text into a readable usage string."""
    header = f"Usage: {command_name} [OPTIONS]"
    lines = [header, "", description, "", "Options:"]

    for flag, help_text in options:
        …
12 0 Open
Functions & basics easy

How to Print Colored Text in Python with ANSI Codes

Define a small Colors class and a colored() helper to print styled terminal text using ANSI escape codes.

ansicodes cli terminal
Python
class Colors:
    RESET = "\033[0m"
    RED = "\033[31m"
    GREEN = "\033[32m"
    YELLOW = "\033[33m"
    BLUE = "\033[34m"
    MAGENTA = "\033[35m"
    CYAN = "\033[36m"
    WHITE = "\033[37m"
    BOLD = "\033[1m"
    UNDERLINE = "\033[4m"


def colored(text, color):
    return f"{color}{text}{Colors.RESET}"


if _…
13 0 Open
Files & data easy

How to Load and Save JSON Files in Python

Load and save JSON files with pretty formatting using Python's standard library json module and pathlib.

json files pathlib
Python
import json
from pathlib import Path


def load_json(filepath: str) -> dict:
    """Load JSON data from a file."""
    path = Path(filepath)
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def save_json(filepath: str, data: dict) -> None:
    """Save data to a JSON file with pretty format…
11 0 Open
OOP & classes easy

How to Create a Data Formatter Class in Python

A beginner-friendly helper class to format lists, dictionaries, and stored records into readable strings.

oop class formatting
Python
class DataFormatter:
    """Helper class for beginners to format common data types."""
    
    def __init__(self, name="data"):
        self.name = name
        self.records = []
    
    def add_record(self, key, value):
        """Add a key-value record to the formatter."""
        self.records.append({"key": key, …
12 0 Open
Comprehensions & generators easy

How to Use List Comprehensions and Generators to Format Data in Python

A beginner-friendly helper that formats dictionaries into strings using a list comprehension and generates squared numbers lazily with a generator.

list comprehension generators formatting
Python
def format_data(items):
    """Format a list of dictionaries into readable strings."""
    formatted = [
        f"{item.get('name', 'Unknown')}: {item.get('value', 0)} units"
        for item in items
        if item.get('value', 0) > 0
    ]
    return formatted if formatted else ["No positive values found"]


def g…
13 0 Open
AI & LLM integration patterns easy

How to Append Few-Shot Examples to a Prompt in Python

This code builds a complete LLM prompt by appending few-shot examples in alternating user/assistant format using a simple loop.

prompt-engineering few-shot llm
Python
def append_few_shot_examples(prompt: str, examples: list[tuple[str, str]], separator: str = "\n\n") -> str:
    """Append few-shot examples to a prompt in alternating user/assistant format."""
    full_prompt = prompt
    for user_input, assistant_output in examples:
        full_prompt = f"{full_prompt}{separator}Use…
15 0 Open
Automation & scripting easy

Fill PDF Form Fields from a Mock Template in Python

Fills a PDF-style form template dictionary with user data, preserving template fields and formatting output as JSON.

pdf forms json
Python
import json

template = {
    "first_name": "",
    "last_name": "",
    "email": "",
    "phone": "",
    "date_of_birth": "",
    "address": "",
    "city": "",
    "state": "",
    "zip_code": "",
    "agree_to_terms": False
}


def fill_pdf_form(template: dict, data: dict) -> dict:
    for key, value in data.items…
10 0 Open
Testing & modern typing easy

Format Data with Type Hints in Python

Build a validated person dict with modern type hints and optional list handling.

type-hints typing data-formatting
Python
from typing import Any, Dict, List, Optional, Union

JsonValue = Union[str, int, float, bool, None, List["JsonValue"], Dict[str, "JsonValue"]]

def format_person(name: str, age: int, hobbies: Optional[List[str]] = None) -> Dict[str, Any]:
    """Build a person dict with validated typing."""
    if not name or age < 0:…
12 0 Open
Testing & modern typing easy

How to Verify Formatted Output with an Approval Test in Python

Write a small Python approval test that verifies a function's exact formatted output using unittest.

approval-testing unittest formatting
Python
import sys
from io import StringIO
import unittest

def generate_output(name, score):
    return f"Player: {name} | Score: {score:03d}"

class TestFormattedOutput(unittest.TestCase):
    def test_output_format(self):
        expected = "Player: Alice | Score: 042"
        result = generate_output("Alice", 42)
        …
13 0 Open
API design & gRPC easy

Format data in Python using dataclasses like gRPC messages

Convert Python dataclasses to and from dicts and format them gRPC-style for clean data handling.

dataclasses grpc serialization
Python
from dataclasses import dataclass
from typing import Any, Dict, List, Optional


@dataclass
class ProductInfo:
    """Data class representing a gRPC-style product message."""

    name: str
    price: float
    tags: List[str]
    description: Optional[str] = None

    def to_dict(self) -> Dict[str, Any]:
        """C…
14 0 Open
Observability & SRE easy

Generate Prometheus Text Exposition Format in Python

Mock a Prometheus metrics endpoint by formatting metrics into the text exposition format with HELP, TYPE, and sample lines.

prometheus metrics observability
Python
import time
from random import randint

# Mock a Prometheus metrics endpoint output
metrics = {
    "http_requests_total": {
        "help": "Total number of HTTP requests",
        "type": "counter",
        "samples": [
            {"labels": {"method": "get", "code": "200"}, "value": randint(1000, 9999)},
         …
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.