Reference library

Python Code Samples

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

44 matches
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 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 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 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 Convert snake_case to Title Case in Python

Convert snake_case strings to title case by splitting on underscores, capitalizing each word, and joining them with spaces.

snake-case string-formatting text-processing
Python
def to_title_case(snake_str):
    words = snake_str.split("_")
    return " ".join(word.capitalize() for word in words)

if __name__ == "__main__":
    examples = ["hello_world", "convert_snake_case", "already_title_case", "multiple__under_scores"]
    for example in examples:
        print(f"{example!r:35} -> {to_tit…
13 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 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 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 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
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 Parse Delimited Data into a Python List

Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.

strings lists loops
Python
def parse_data(raw_data):
    """Parse a pipe-delimited string into a list of cleaned items."""
    items = raw_data.split("|")
    parsed = []
    for item in items:
        cleaned = item.strip()
        if cleaned:
            parsed.append(cleaned)
    return parsed


if __name__ == "__main__":
    data = "  apple…
15 0 Open
Lists & loops easy

How to Partition a List Around a Pivot in Python

This code splits a list into three parts—elements less than, equal to, and greater than a pivot—then concatenates them to produce a partitioned list while preserving the original order within each group.

partition list pivot
Python
def partition_list(lst, pivot):
    less = []
    equal = []
    greater = []
    for item in lst:
        if item < pivot:
            less.append(item)
        elif item == pivot:
            equal.append(item)
        else:
            greater.append(item)
    return less + equal + greater

if __name__ == "__main__…
14 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 Split a List at the First Occurrence of a Value in Python

This function splits a list into two parts at the first occurrence of a given value, returning the left and right portions.

list slicing split
Python
def split_at_first(lst, value):
    try:
        idx = lst.index(value)
        return lst[:idx], lst[idx:]
    except ValueError:
        return lst, []

if __name__ == "__main__":
    sample = [1, 2, 3, 4, 3, 5]
    value = 3
    left, right = split_at_first(sample, value)
    print("Left:", left)
    print("Right:"…
13 0 Open
Lists & loops easy

How to Split a List into Chunks in Python

Split a list into fixed-size sublists using a simple list comprehension with slicing.

list slicing chunking
Python
def chunk_list(lst, size):
    """Split a list into sublists of given size."""
    return [lst[i:i + size] for i in range(0, len(lst), size)]


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(chunk_list(sample, 3))
13 0 Open
Lists & loops easy

How to split a list by condition in Python

Splits a list into two lists based on a condition function, returning matched and unmatched items.

lists condition partition
Python
def split_by_condition(items, condition):
    """
    Split a list into two lists based on a condition.
    The first list contains items where condition(item) is True,
    the second list contains the rest.
    """
    matched = []
    unmatched = []
    for item in items:
        if condition(item):
            matc…
11 0 Open
Lists & loops easy

How to unzip a list of pairs into two lists in Python

Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.

lists tuples loops
Python
def unzip(pairs):
    """Split a list of (a, b) pairs into two separate lists."""
    if not pairs:
        return [], []
    
    firsts = []
    seconds = []
    for a, b in pairs:
        firsts.append(a)
        seconds.append(b)
    
    return firsts, seconds


if __name__ == "__main__":
    pairs = [(1, 'a'), (…
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.