Reference library

Python Code Samples

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

1561 matches
Strings & text easy

How to Extract Digits Only from a String in Python

This code uses a regular expression to remove all non-digit characters from a mixed string, returning only the digits.

regex string manipulation data cleaning
Python
import re

def extract_digits(text):
    """Return only the digits from the given text as a string."""
    return re.sub(r'\D', '', text)

if __name__ == "__main__":
    mixed = "abc123def456!@#789"
    result = extract_digits(mixed)
    print(result)
12 0 Open
Strings & text easy

How to Filter Text to Only Letters, Numbers, and Spaces in Python

A beginner-friendly function that filters a string to keep only alphabetic characters, digits, and spaces, removing punctuation and symbols.

text-filtering strings beginner
Python
def filter_text(text, keep_alpha=True, keep_digits=True, keep_spaces=True):
    allowed = set()
    if keep_alpha:
        allowed.update("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    if keep_digits:
        allowed.update("0123456789")
    if keep_spaces:
        allowed.add(" ")
    return "".join(ch f…
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 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 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 Group Data by Category in Python

Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.

grouping dictionaries setdefault
Python
def group_by_category(data):
    """Group list of (category, value) tuples into dictionaries of lists."""
    groups = {}
    for category, value in data:
        groups.setdefault(category, []).append(value)
    return groups

if __name__ == "__main__":
    items = [
        ("fruit", "apple"),
        ("veg", "carro…
12 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 Join List of Words into a Sentence in Python

Concatenate a list of strings into a single sentence with spaces using the Python string join() method.

string join list
Python
words = ["Hello", "world", "this", "is", "Python"]
sentence = " ".join(words)
print(sentence)
15 0 Open
Strings & text easy

How to Mask Credit Card Middle Digits in Python

Mask the middle digits of credit card numbers in a string, keeping only the first 8 and last 4 digits, using regular expressions.

regex string-manipulation security
Python
import re

def mask_credit_card(text: str) -> str:
    pattern = re.compile(r'(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4})')
    return pattern.sub(lambda m: m.group(1) + m.group(2) + '****' + m.group(4), text)

if __name__ == "__main__":
    sample = "Card: 1234-5678-9012-3456 and 1111 2222 3333 4444"
    print(mas…
13 0 Open
Strings & text easy

How to Normalize Text in Python

This code defines a function that trims, lowercases, and collapses extra whitespace in a string, returning normalized text.

string normalization whitespace
Python
def normalize_text(text: str) -> str:
    normalized = " ".join(text.lower().strip().split())
    return normalized


if __name__ == "__main__":
    raw = "   Hello,   WORLD!   This is   a  test.   "
    print(normalize_text(raw))
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 Partition a String on the First Delimiter in Python

Split a string into a tuple of (before, delimiter, after) at the first occurrence of a given delimiter, using a custom function or the built-in str.partition.

string partition split
Python
def partition_string(s, delimiter):
    """Split string into (before, delimiter, after) on the first occurrence."""
    for i, ch in enumerate(s):
        if ch == delimiter:
            return s[:i], ch, s[i+1:]
    return s, "", ""


if __name__ == "__main__":
    # Single-character delimiter
    s1 = "hello,world,h…
13 0 Open
Strings & text easy

How to Process Text in Python: Normalize Whitespace and Count Words

A beginner-friendly function that normalizes whitespace in a string and counts total and unique words using Python's standard library.

strings text-processing word-count
Python
def process_text(text):
    """Basic text processing: normalize whitespace and count words."""
    normalized = " ".join(text.split())
    word_count = len(normalized.split())
    char_count = len(normalized)
    
    # Count unique words
    unique_words = set(normalized.lower().split())
    unique_count = len(unique…
12 0 Open
Strings & text easy

How to Remove Duplicate Adjacent Spaces in Python

This Python function collapses any sequence of two or more adjacent spaces into a single space, preserving all other characters.

strings whitespace text-cleaning
Python
def remove_duplicate_adjacent_spaces(text):
    """Replace sequences of 2+ spaces with a single space."""
    result = []
    prev_was_space = False
    for char in text:
        if char == " ":
            if not prev_was_space:
                result.append(char)
            prev_was_space = True
        else:
     …
12 0 Open
Strings & text easy

How to Remove HTML Tags in Python with Regex

Strips all HTML tags from a string using a regular expression and cleans extra whitespace.

regex html text-cleaning
Python
import re

def remove_html_tags(text: str) -> str:
    """Remove all HTML tags from the given text using regex."""
    # Remove opening and closing tags
    clean = re.sub(r'<[^>]+>', '', text)
    # Remove any extra whitespace left behind
    clean = re.sub(r'\s+', ' ', clean).strip()
    return clean

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

How to Replace Multiple Spaces with a Single Space in Python

This snippet uses the `re` module to collapse runs of consecutive spaces in a string into a single space, cleaning up whitespace.

regex strings whitespace
Python
import re

def collapse_spaces(text):
    """Replace multiple consecutive spaces with a single space."""
    return re.sub(r' +', ' ', text)

if __name__ == "__main__":
    sample = "This   has   multiple    spaces   between words."
    result = collapse_spaces(sample)
    print(f"Original: '{sample}'")
    print(f"Co…
15 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 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 Split Lines and Strip Blank Lines in Python

Split a multiline string into non-empty lines and strip surrounding whitespace using a list comprehension.

string splitlines strip
Python
import sys

def split_and_strip(text):
    """Split text into non-blank lines, stripping whitespace."""
    return [line.strip() for line in text.splitlines() if line.strip()]

if __name__ == "__main__":
    sample_text = """  First line   
    
    Second line	
      
    Third line  """
    result = split_and_strip(…
12 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 Split a String by Comma in Python

Splits a comma-separated string into a list of trimmed items using Python's built-in split and a list comprehension.

strings split list
Python
def split_csv(line):
    return [item.strip() for item in line.split(",")]

if __name__ == "__main__":
    sample = "apple, banana, cherry, date"
    result = split_csv(sample)
    print(result)
    print(f"Number of items: {len(result)}")
11 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.