Reference library

Python Code Samples

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

8 matches
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 Convert and Process Text in Python

This code cleans, converts, splits, joins, counts, replaces, reverses, and finds substrings in a text string using Python's standard string methods.

strings text processing methods
Python
text = "  hello world, python is fun!  "

# Clean up whitespace
cleaned = text.strip()

# Convert to title case
titled = cleaned.title()

# Split into words
words = cleaned.split()

# Join with hyphens
hyphenated = "-".join(words)

# Count occurrences of a letter
letter_count = cleaned.count("o")

# Replace a word
rep…
11 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 Generate Initials from a Full Name in Python

Extract and uppercase the first letter of each word in a full name to produce initials using standard string methods.

strings initialism text-processing
Python
def generate_initials(full_name):
    parts = full_name.strip().split()
    initials = ''.join(part[0].upper() for part in parts if part)
    return initials

if __name__ == "__main__":
    name = "john f. kennedy"
    print(generate_initials(name))
14 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

Text Processor Functions for Beginners in Python

Demonstrates simple text-processing utilities: word counting, word reversal, whitespace normalization, and lowercase conversion using basic string methods.

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

def reverse_words(text):
    """Return the text with words in reverse order."""
    return ' '.join(text.split()[::-1])

def remove_extra_spaces(text):
    """Return text with extra whitespace collapsed to a single s…
13 0 Open
Lists & loops easy

How to Parse Bullet Points in Python

Extract bullet point items from raw text by splitting lines and filtering those that start with '- ' or '* '.

text parsing bullet points loops
Python
def parse_bullet_points(text):
    """Extract bullet point items from raw text."""
    lines = text.splitlines()
    items = []
    
    for line in lines:
        stripped = line.strip()
        if stripped.startswith("- ") or stripped.startswith("* "):
            item = stripped[2:]
            if item:
           …
13 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.