Reference library

Python Code Samples

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

63 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 Check and Manipulate Strings in Python

Demonstrates core string inspection and transformation methods like case conversion, trimming, splitting, and membership checks on a sample string.

strings text-processing beginners
Python
text = "  Hello, Python Learners!  "

print(f"Original: '{text}'")
print(f"Lowercase: '{text.lower()}'")
print(f"Uppercase: '{text.upper()}'")
print(f"Title case: '{text.title()}'")
print(f"Stripped: '{text.strip()}'")
print(f"Length: {len(text)}")
print(f"Replace: '{text.replace('Python', 'Programming')}'")
print(f"S…
15 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…
11 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 Strings with Named Placeholders in Python

Format a template string using named placeholders with the str.format() method and a dictionary.

string format placeholders
Python
def format_named(template, data):
    """Format a template string using named placeholders."""
    return template.format(**data)


if __name__ == "__main__":
    template = "Hello {name}, you are {age} years old and live in {city}."
    data = {"name": "Alice", "age": 30, "city": "London"}
    result = format_named(t…
15 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 Inspect String Statistics in Python

A beginner-friendly function that returns detailed statistics about a string, including length, word count, character types, and easy text transformations.

strings text-analysis statistics
Python
def inspect_text(text: str) -> dict:
    """Return useful stats about a string for beginners."""
    words = text.split()
    return {
        "length": len(text),
        "word_count": len(words),
        "uppercase": sum(1 for ch in text if ch.isupper()),
        "lowercase": sum(1 for ch in text if ch.islower()),
 …
14 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 Transform Text in Python with a Helper Function

Build a simple Python helper to strip extra whitespace and convert text to upper, lower, or title case.

strings text helper
Python
def transform_text(text, upper=False, lower=False, strip_whitespace=False, title_case=False):
    """Apply common string transformations for beginners."""
    result = text

    if strip_whitespace:
        result = " ".join(result.split())

    if upper and lower:
        raise ValueError("Cannot apply both upper and…
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
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@…
12 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
Lists & loops easy

How to check list items by type and emptiness in Python

Loop through a list with enumerate(), classify each item as empty, number, or text, and print a formatted status for each element.

lists loops enumerate
Python
def check_data(data):
    """Check each item in a list and print whether it's valid."""
    for i, item in enumerate(data):
        if item is None or item == "":
            status = "empty"
        elif isinstance(item, (int, float)):
            status = "number"
        else:
            status = "text"
        pr…
14 0 Open
Lists & loops easy

Replace Negative Values in a List with Python

This code defines a function that replaces every negative number in a list with a replacement value, defaulting to zero, using a list comprehension.

list-comprehension data-cleaning list-transformation
Python
def replace_if_negative(values, replacement=0):
    return [replacement if value < 0 else value for value in values]

if __name__ == "__main__":
    numbers = [5, -3, 8, -1, 0, -7, 2]
    result = replace_if_negative(numbers)
    print(f"Original: {numbers}")
    print(f"Replaced: {result}")
14 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
Errors & debugging easy

How to Assert an Invariant After a Complex Transformation in Python

Use assert to verify that a multi-step transformation preserves a mathematical invariant, catching regressions early.

assert debugging invariants
Python
def transform_value(value):
    """Apply several transformations to a value."""
    doubled = value * 2
    shifted = doubled + 10
    normalized = shifted / 2
    return int(normalized)

def assert_invariant(value):
    """Assert that the transformation preserves a key invariant."""
    original = value
    transform…
13 0 Open
Errors & debugging easy

How to Log Exceptions with traceback.format_exc in Python

Capture and log a full traceback string when an exception occurs using Python's traceback.format_exc() and logging module.

traceback logging exception
Python
import traceback
import logging

def risky_operation(value):
    return 10 / value

logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')

def main():
    try:
        result = risky_operation(0)
        print(f"Result: {result}")
    except ZeroDivisionError:
        error_msg =…
14 0 Open
Errors & debugging easy

How to Raise a Custom Exception with Extra Context in Python

Define a custom exception that carries extra context fields and raise it to provide richer error information.

exceptions custom-exception error-handling
Python
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Withdrawal of ${amount} failed: balance ${balance} is insufficient")


def withdraw(balance, amount):
    if amount > balance:
        raise Insuffici…
13 0 Open
Errors & debugging easy

Log to stderr with Python logging basicConfig

Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.

logging stderr debugging
Python
import logging

def main():
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
        stream=__import__("sys").stderr,
    )
    logger = logging.getLogger("example")
    logger.debug("Debug message")
    logger.info("Info message")
    logger.…
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.