Reference library

Python Code Samples

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

316 matches
Strings & text easy

Build a Secure Password Strength Checker in Python

A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.

password security regex
Python
import re

def password_strength(password: str) -> str:
    score = 0
    if len(password) >= 8:
        score += 1
    if re.search(r'[a-z]', password):
        score += 1
    if re.search(r'[A-Z]', password):
        score += 1
    if re.search(r'\d', password):
        score += 1
    if re.search(r'[!@#$%^&*(),.?":…
54 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

Find Most Frequent Character in a String in Python

Count character frequencies in a Python string using a dictionary and return the character that appears most often with a max() key function.

string dictionary counting
Python
def most_frequent_char(s: str) -> str:
    if not s:
        return ""
    
    char_count = {}
    for ch in s:
        char_count[ch] = char_count.get(ch, 0) + 1
    
    max_char = max(char_count, key=char_count.get)
    return max_char

if __name__ == "__main__":
    text = "programming"
    result = most_frequent…
12 0 Open
Strings & text easy

Find the Longest Word in a Sentence in Python

Splits a sentence into words and returns the longest one using the built-in max() function with len as the key.

strings max split
Python
def find_longest_word(sentence: str) -> str:
    words = sentence.split()
    if not words:
        return ""
    return max(words, key=len)

if __name__ == "__main__":
    test_sentence = "The quick brown fox jumps over the lazy dog"
    longest = find_longest_word(test_sentence)
    print(f"Longest word: '{longest}'…
14 0 Open
Strings & text easy

How to Build a Text Processor in Python

This code defines functions to count words, sentences, and find the longest word in a text, then prints basic statistics like uppercase and lowercase versions.

text-processing strings word-count
Python
def count_words(text):
    return len(text.split())


def count_sentences(text):
    sentence_endings = ".!?"
    count = 0
    for char in text:
        if char in sentence_endings:
            count += 1
    return count


def longest_word(text):
    words = text.split()
    if not words:
        return ""
    retur…
14 0 Open
Strings & text easy

How to Check if a String Starts With a Prefix Case-Insensitively in Python

This code defines a function that checks if a string starts with a given prefix, ignoring case, using the lower() method.

string-methods case-insensitive startswith
Python
def starts_with_case_insensitive(text, prefix):
    """Check if a string starts with a given prefix, ignoring case."""
    return text.lower().startswith(prefix.lower())


if __name__ == "__main__":
    test_strings = [
        ("Hello World", "hello"),
        ("Python Programming", "PYTHON"),
        ("Data Science"…
14 0 Open
Strings & text easy

How to Check if a String is Numeric in Python

This code provides a function to determine if a string represents a valid numeric value using Python's built-in float() conversion.

numeric validation strings
Python
def is_numeric(s):
    """Check if a string represents a valid numeric value."""
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

if __name__ == "__main__":
    test_cases = ["123", "-45.67", "3.14e10", "0x1A", "abc", "12.5.6", "  42  ", ""]
    for case in test_c…
13 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 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…
10 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",
…
16 0 Open
Strings & text easy

How to Encode and Decode UTF-8 in Python

Convert a Python string to UTF-8 bytes with .encode() and back to text with .decode(), with a simple demo function.

utf-8 encode decode
Python
def encode_decode_demo(text: str):
    encoded = text.encode("utf-8")
    decoded = encoded.decode("utf-8")
    print(f"Original string: {text}")
    print(f"Encoded bytes: {encoded}")
    print(f"Decoded string: {decoded}")
    print(f"Match: {text == decoded}")

if __name__ == "__main__":
    encode_decode_demo("Hel…
13 0 Open
Strings & text easy

How to Escape HTML in Python

This code demonstrates how to use Python's `html.escape` function to safely encode user input for display in HTML, preventing XSS attacks.

html escaping security
Python
import html

def escape_user_input(user_input: str) -> str:
    """Escape HTML-sensitive characters for safe display."""
    return html.escape(user_input)

if __name__ == "__main__":
    sample_user_input = '<script>alert("XSS")</script> & \'quotes\''
    safe_output = escape_user_input(sample_user_input)
    print("…
13 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…
10 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 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)}")
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…
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 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))
13 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…
12 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:
     …
11 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…
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.