Reference library

Python Code Samples

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

118 matches
Strings & text easy

Extract Data from Strings in Python: Beginner's Guide

A beginner-friendly helper that splits a comma-separated string into a list, shows word count, and extracts the first and last words using Python's split() and join() methods.

string split join
Python
text = "python,string,extract,beginner"

words = text.split(",")

print("Full text:", text)
print("Word count:", len(words))
print("First word:", words[0])
print("Last word:", words[-1])

joined = " | ".join(words)
print("Joined with separator:", joined)
15 0 Open
Strings & text easy

Find Data From a String in Python: Stats, Clean, Keywords

Three helper functions for beginners: compute character/word/sentence stats, normalize whitespace and case, and extract unique sorted keywords from a string.

strings text-processing keywords
Python
def get_text_stats(text):
    """Return basic statistics about a string."""
    words = text.split()
    sentences = text.replace('!', '.').replace('?', '.').split('.')
    sentences = [s for s in sentences if s.strip()]
    return {
        'characters': len(text),
        'words': len(words),
        'sentences': le…
14 0 Open
Strings & text easy

How to Compare Two Strings in Python

Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.

string-comparison case-insensitive helper-function
Python
def compare_data(first_value, second_value):
    """Compare two string values and return a report."""
    if first_value == second_value:
        status = "MATCH"
    else:
        status = "DIFFER"
    return {
        "first_value": first_value,
        "second_value": second_value,
        "status": status,
       …
12 0 Open
Strings & text easy

How to Convert Data to Strings in Python

Convert common data types like bytes, numbers, containers, and None to readable strings with a safe helper function.

strings conversion type-conversion
Python
def to_str(value):
    """Convert common types to a readable string, safe for beginners."""
    if isinstance(value, bytes):
        return value.decode("utf-8")
    if isinstance(value, (dict, list, tuple, set)):
        return str(value)
    if value is None:
        return ""
    return str(value)


if __name__ == …
11 0 Open
Strings & text easy

How to Filter a List of Strings by Keyword in Python

A helper function filters a list of strings by a keyword search with optional case sensitivity.

string filter list
Python
def filter_strings(items, keyword, case_sensitive=False):
    """
    Filter a list of strings by a keyword.
    
    Args:
        items: list of strings to filter
        keyword: substring to search for
        case_sensitive: if True, match case exactly
    
    Returns:
        list of strings containing the keyw…
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 Generate Text Helper Functions in Python

Three simple Python functions that repeat, join, and count characters in strings for beginners.

strings text-processing functions
Python
def repeat_text(text, times):
    """Repeat a string a given number of times."""
    return text * times


def join_words(words, separator=" "):
    """Join a list of words into a single string."""
    return separator.join(words)


def count_characters(text):
    """Count character occurrences in a string."""
    ret…
14 0 Open
Strings & text easy

How to Merge Strings in Python

Merge multiple strings or a list of text lines into one string with a custom separator

strings join merging
Python
def merge_strings(*parts, separator=" "):
    """Merge multiple string parts into one string with a separator."""
    return separator.join(parts)


def merge_text_lines(lines, separator="\n"):
    """Merge a list of text lines into a single string."""
    return separator.join(lines)


if __name__ == "__main__":
    …
15 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 Sort Text in Python with a Simple Helper Function

A compact helper function that sorts a list of strings or splits a string into words and sorts them alphabetically, with optional reverse ordering.

sorting strings text-processing
Python
def sort_text(data, reverse=False):
    """
    Sort a list of strings (or a single string split into words) alphabetically.
    """
    if isinstance(data, str):
        words = data.split()
    else:
        words = [str(item) for item in data]
    return sorted(words, reverse=reverse)


if __name__ == "__main__":
 …
11 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 Validate Text Strings in Python

Validate strings with a reusable helper that checks type, length limits, and empty string handling.

validation strings helper-function
Python
def is_valid_text(value, min_length=1, max_length=None, allow_empty=False):
    """
    Validate if a value is a string and meets length requirements.
    
    Args:
        value: The value to validate
        min_length: Minimum allowed length (default 1)
        max_length: Maximum allowed length (None = no limit)
…
13 0 Open
Strings & text easy

How to build a text helper in Python for beginners

This code provides easy-to-use functions for cleaning text, removing punctuation, counting word frequencies, and summarizing strings — perfect for beginners.

string-manipulation text-processing word-count
Python
def clean_text(text: str) -> str:
    """Clean and normalize a text string."""
    text = text.strip()
    text = text.replace("  ", " ")
    text = text.capitalize()
    text = text.replace(".", ".")
    return text


def remove_punctuation(text: str) -> str:
    """Remove common punctuation marks from a string."""
 …
12 0 Open
Strings & text easy

Python String Helper Functions for Beginners

A set of beginner-friendly Python functions that count words, reverse text, convert to title case, strip punctuation, and compute character frequency from a string.

strings text-processing word-count
Python
def count_words(text):
    """Count the number of words in a string."""
    return len(text.split())


def reverse_text(text):
    """Reverse the entire string."""
    return text[::-1]


def title_case(text):
    """Capitalize the first letter of each word."""
    return text.title()


def remove_punctuation(text):
 …
14 0 Open
Strings & text easy

String helpers in Python: stats, reverse, and remove vowels

Three beginner-friendly Python functions compute text statistics, reverse word order, and strip vowels from a string.

string-manipulation text-stats vowel-removal
Python
def text_stats(text: str) -> dict:
    """Return basic statistics for a given text string."""
    words = text.split()
    return {
        "characters": len(text),
        "words": len(words),
        "sentences": text.count(".") + text.count("!") + text.count("?"),
        "uppercase": sum(1 for c in text if c.isupp…
14 0 Open
Lists & loops easy

Compare Two Lists in Python: Common, Only in First, Only in Second

A beginner-friendly helper that loops over two lists and returns items common to both, items only in the first list, and items only in the second list.

lists comparison loops
Python
def compare_lists(list1, list2):
    common = []
    only_in_first = []
    only_in_second = []
    
    for item in list1:
        if item in list2:
            common.append(item)
        else:
            only_in_first.append(item)
    
    for item in list2:
        if item not in list1:
            only_in_second…
14 0 Open
Lists & loops easy

Generate Data Helper for Beginners in Python

Define two functions that create a random list of integers and then compute basic summary statistics like count, total, average, maximum, and minimum using simple loops.

random loops lists
Python
from random import randint

def build_dataset(size: int, max_val: int) -> list[int]:
    data = []
    for _ in range(size):
        data.append(randint(1, max_val))
    return data

def summarize(data: list[int]) -> dict[str, float]:
    total = 0
    maximum = data[0]
    minimum = data[0]
    for value in data:
   …
12 0 Open
Lists & loops easy

How to Filter Even Numbers and Square Them in Python

Create two beginner-friendly helper functions that filter even numbers and compute squares of a number list using loops, then print the results along with the sum and average.

loops filtering math
Python
def get_even_numbers(numbers):
    evens = []
    for num in numbers:
        if num % 2 == 0:
            evens.append(num)
    return evens

def get_squares(numbers):
    squares = []
    for num in numbers:
        squares.append(num ** 2)
    return squares

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers …
15 0 Open
Lists & loops easy

How to Validate List Data in Python

A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.

validation lists loops
Python
def validate_data(data, expected_types=None, min_length=1):
    """Validate that data is a non-empty list and optionally check item types."""
    if not isinstance(data, list):
        return False, f"Expected a list, got {type(data).__name__}"
    
    if len(data) < min_length:
        return False, f"List must have…
16 0 Open
Functions & basics easy

How to Compose Two Functions into a Single Callable in Python

Combine two Python functions into a single callable using a compose helper, then apply the chained call.

functions composition lambda
Python
def add_one(x):
    return x + 1

def double(x):
    return x * 2

def compose(f, g):
    return lambda x: f(g(x))

add_then_double = compose(double, add_one)
double_then_add = compose(add_one, double)

result1 = add_then_double(5)
result2 = double_then_add(5)

print(f"add_one then double(5) = {result1}")
print(f"doub…
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

File Data Helper Functions in Python

Read and write text and JSON files, and list files in a directory, using pathlib-based helper functions.

file-io pathlib json
Python
from pathlib import Path

def load_text_file(filepath):
    """Read a text file and return its contents as a string."""
    path = Path(filepath)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {filepath}")
    return path.read_text(encoding="utf-8")

def save_text_file(filepath, content):
…
14 0 Open
Files & data easy

How to List File Information in a Directory with Python

A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.

pathlib filesystem file-metadata
Python
from pathlib import Path


def get_files_data(directory: str) -> list[dict]:
    """Return basic info about all files in a directory."""
    files = []
    for path in Path(directory).iterdir():
        if path.is_file():
            files.append({
                "name": path.name,
                "size": path.stat()…
12 0 Open
Files & data easy

How to Merge Dicts from Two JSON Files Like a Pro

This helper reads two JSON files that contain dicts, merges them with the second file overriding duplicate keys, and saves the result to a new file.

json dict merge
Python
import json
from pathlib import Path


def merge_json_files(file1: str, file2: str, output: str = "merged.json") -> dict:
    """Merge two JSON files containing dicts, with file2 overriding file1."""
    data1 = json.loads(Path(file1).read_text())
    data2 = json.loads(Path(file2).read_text())

    merged = {**data1,…
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.