Reference library

Python Code Samples

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

96 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

Count Characters, Words, and Lines in Python Text

Counts characters, words, lines, and the most common words in a given string using Python's standard library.

text-analysis counter strings
Python
from collections import Counter


def count_data(text):
    """Count characters, words, lines, and most common words in text."""
    char_count = len(text)
    word_count = len(text.split())
    line_count = text.count("\n") + 1
    word_freq = Counter(text.lower().split())
    most_common = word_freq.most_common(3)

…
17 0 Open
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

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}'…
15 0 Open
Strings & text easy

How to Build a Basic Text Processor in Python

Split text into sentences, count words, find the longest word, and convert text to uppercase — all with pure Python string methods.

string text-processing split
Python
text = """The quick brown fox jumps over the lazy dog.
Python is a powerful programming language.
Keep practicing every single day!"""

sentences = text.split(". ")
word_count = 0
longest_word = ""

for sentence in sentences:
    words = sentence.split()
    word_count += len(words)
    for word in words:
        clea…
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 Count Words in a String in Python

Split a paragraph on whitespace and return the number of words using Python's built-in string methods.

strings word-count split
Python
def count_words(paragraph: str) -> int:
    words = paragraph.split()
    return len(words)


if __name__ == "__main__":
    paragraph = "The quick brown fox jumps over the lazy dog."
    result = count_words(paragraph)
    print(f"Word count: {result}")
13 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 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 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 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 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 Sort Text Alphabetically in Python

Sort words or lines alphabetically with case-insensitive ordering while preserving original casing.

sorting text-processing strings
Python
def sort_words(text):
    """Sort words alphabetically (case-insensitive), preserving case."""
    words = text.split()
    return sorted(words, key=str.lower)


def sort_lines(text):
    """Sort lines alphabetically (case-insensitive), preserving case."""
    lines = [line for line in text.splitlines() if line.strip(…
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

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

Reverse Words in a Sentence While Keeping Punctuation in Python

Reverses the order of words in a sentence while leaving punctuation and spaces in their original positions using Python's re module.

strings punctuation regex
Python
def reverse_words_preserving_punctuation(sentence: str) -> str:
    import re
    # Split into words and punctuation tokens
    tokens = re.findall(r'\w+|[^\w\s]|\s+', sentence)
    words = [t for t in tokens if re.fullmatch(r'\w+', t)]
    words.reverse()
    result_parts = []
    word_index = 0
    for token in toke…
13 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

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 Process Text into Words in Python

Splits a string into words, strips punctuation, and returns a list of uppercase words using a loop.

text-processing loops strings
Python
def convert_text_processor(text):
    words = text.split()
    processed = []
    
    for word in words:
        clean = word.strip('.,!?;:')
        if len(clean) > 0:
            processed.append(clean.upper())
    
    return processed

if __name__ == "__main__":
    sample_text = "Hello, world! This is a Python e…
12 0 Open
Lists & loops easy

How to Process Text with Lists and Loops in Python

A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.

lists loops strings
Python
text = "Python makes text processing easy and fun"

words = text.lower().split()

print("Words in the sentence:")
for index, word in enumerate(words, start=1):
    print(f"{index}. {word}")

filtered_words = [word for word in words if len(word) > 3]

print(f"\nWords longer than 3 characters: {filtered_words}")

letter…
14 0 Open
Lists & loops easy

How to Process Text with Lists and Loops in Python

Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.

lists loops enumerate
Python
# text_processor.py

def process_text(lines):
    """Count words, show uppercase, and count characters per line."""
    total_words = 0
    print("Line-by-line analysis:")
    for i, line in enumerate(lines, start=1):
        words = line.split()
        total_words += len(words)
        print(f"  Line {i}: {len(words…
17 0 Open
Lists & loops easy

How to Validate Text Against Forbidden Words in Python

Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.

text validation lists loops
Python
def validate_text(text, forbidden_words):
    """
    Checks that text does not contain any forbidden words.
    Returns (is_valid, offending_words) tuple.
    """
    words = text.lower().split()
    found = [word for word in words if word in forbidden_words]
    return len(found) == 0, found


if __name__ == "__main…
14 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.