Reference library

Python Code Samples

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

382 matches
Strings & text easy

Automatically Detect Weak Passwords from Large Password Lists in Python

This Python script identifies weak passwords from a list by checking length, common patterns, sequential characters, and uniform characters, returning those that fail the security checks.

password security validation
Python
import re

COMMON_PASSWORDS_FILE = "common_passwords.txt"

def is_weak(password):
    # Check length
    if len(password) < 8:
        return True
    # Check for common patterns
    if password.lower() in {"password", "123456", "qwerty", "letmein", "admin", "welcome"}:
        return True
    # Check for sequential c…
54 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 Detect if a String Contains Only ASCII in Python

This code defines a function that checks whether every character in a given string is an ASCII character (Unicode code point < 128) and demonstrates it with multiple test cases.

ascii string validation
Python
def is_ascii_only(text: str) -> bool:
    """Return True if all characters in text are ASCII, False otherwise."""
    return all(ord(char) < 128 for char in text)


if __name__ == "__main__":
    # Test cases
    samples = [
        "Hello, world!",
        "Café au lait",
        "日本語テキスト",
        "ASCII only 123",
…
17 0 Open
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 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 Join Multiline Text with a Semicolon Separator in Python

This code joins non-empty lines of multiline text into a single string separated by semicolons, stripping leading and trailing whitespace from each line.

multiline join separator
Python
def join_multiline_text_with_semicolon(text):
    """Join lines of multiline text with a semicolon separator."""
    lines = [line.strip() for line in text.splitlines() if line.strip()]
    return "; ".join(lines)


if __name__ == "__main__":
    sample_text = """First line
Second line
Third line"""
    result = join_…
13 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 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 Process Lines of Text in Python

Strip whitespace, split a multi-line string, count words per line, and print structured summaries using basic string methods and loops.

strings text-processing splitlines
Python
text = """   Python is great!
Coding is fun.
   Python skills help you grow.   """

lines = text.strip().splitlines()
line_count = len(lines)

processed = []
for line in lines:
    stripped = line.strip()
    word_count = len(stripped.split())
    processed.append({
        "original": line,
        "stripped": stripp…
13 0 Open
Strings & text easy

How to Process Text in Python

This code processes multiline text by splitting lines, stripping whitespace, counting words and characters, and converting to lowercase.

text-processing strings beginner
Python
def process_text(text):
    lines = text.split("\n")
    clean_lines = []
    for line in lines:
        stripped = line.strip()
        if stripped:
            tokens = stripped.split()
            title_case = stripped.lower()
            clean_lines.append({
                "raw": stripped,
                "word_c…
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 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 Strip Whitespace in Python

This code demonstrates how to remove leading and trailing whitespace from a string using the built-in strip() method.

string whitespace text-cleaning
Python
def strip_whitespace(text: str) -> str:
    return text.strip()

if __name__ == "__main__":
    sample = "   Hello, world!   "
    result = strip_whitespace(sample)
    print(f"Original: '{sample}'")
    print(f"Stripped: '{result}'")
14 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 Truncate a String with Ellipsis in Python

A function that shortens text to a maximum length and appends an ellipsis when truncation occurs, handling edge cases.

strings truncation text-processing
Python
def truncate_with_ellipsis(text: str, max_length: int) -> str:
    """Truncate text to max_length, appending ellipsis if truncated."""
    if len(text) <= max_length:
        return text
    if max_length <= 3:
        return text[:max_length]
    return text[: max_length - 3] + "..."

if __name__ == "__main__":
    t…
11 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

Python: Replace Spaces with Hyphens for Slug

Transform a string by stripping surrounding whitespace and replacing each space with a hyphen to create a simple slug.

strings replace slug
Python
def slugify(text):
    return text.strip().replace(" ", "-")

if __name__ == "__main__":
    title = "Hello World Python Example"
    result = slugify(title)
    print(result)
12 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

Find Duplicate Elements in a Python List

Identifies and returns duplicate elements from a Python list using sets for efficient membership tests.

duplicates sets list
Python
def find_duplicates(lst):
    seen = set()
    duplicates = set()
    for item in lst:
        if item in seen:
            duplicates.add(item)
        else:
            seen.add(item)
    return list(duplicates)

if __name__ == "__main__":
    sample = [1, 2, 3, 2, 4, 1, 5, 3]
    print(find_duplicates(sample))
12 0 Open
Lists & loops easy

How to Build a Text Processor with Lists and Loops in Python

A beginner-friendly Python script that analyzes text by counting sentences, words, and word lengths using lists and for loops, then prints the results.

text-processing loops lists
Python
def process_text(text):
    """Simple text processor for beginners using lists and loops."""
    sentences = text.replace('!', '.').replace('?', '.').split('.')
    words = text.split()
    
    word_counts = []
    for sentence in sentences:
        sentence_word_count = len(sentence.split())
        word_counts.appe…
12 0 Open
Lists & loops easy

How to Filter Empty Strings in Python

Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.

filtering strings list-comprehension
Python
def filter_empty_strings(strings):
    """
    Filter out empty strings (including whitespace-only strings)
    from a list of strings.
    """
    return [s for s in strings if s.strip()]


if __name__ == "__main__":
    sample_list = ["hello", "", "world", "   ", "python", " ", "!"]
    filtered = filter_empty_strin…
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.