Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Validate Text Input in Python: A Simple Text Processor
A Python function that validates a text string by trimming whitespace, then returns a dictionary with character, word, and sentence counts.
def validate_text(text: str) -> dict:
"""Analyze a text string and return basic validation statistics."""
stripped = text.strip()
if not stripped:
return {
"valid": False,
"reason": "Text is empty or only whitespace",
"characters": 0,
"words": 0,
…
How to Validate Text Strings in Python
Validate strings with a reusable helper that checks type, length limits, and empty string handling.
def is_valid_text(value, min_length=1, max_length=None, allow_empty=False):
"""
Validate if a value is a string and meets length requirements.
Args:
value: The value to validate
min_length: Minimum allowed length (default 1)
max_length: Maximum allowed length (None = no limit)
…
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.
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."""
…
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.
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):
…
Python String isalpha() Method: Check if String is Alphabetic
This code defines a function that uses Python's str.isalpha() method to determine if a string contains only alphabetic characters, with a demonstration on several test strings.
def is_alphabetic(s):
return s.isalpha()
if __name__ == "__main__":
test_strings = ["Hello", "Hello123", "World!", "Python", ""]
for s in test_strings:
print(f"{s!r}: {is_alphabetic(s)}")
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.
def slugify(text):
return text.strip().replace(" ", "-")
if __name__ == "__main__":
title = "Hello World Python Example"
result = slugify(title)
print(result)
Remove Substring Occurrences Case-Insensitively in Python
This code removes every case-insensitive occurrence of a given substring from a text string using a simple looping approach.
def remove_occurrences_ci(text: str, substring: str) -> str:
"""Remove all case-insensitive occurrences of substring from text."""
if not substring:
return text
result = []
i = 0
lower_text = text.lower()
lower_sub = substring.lower()
sub_len = len(substring)
while i <…
Repeat a string n times with a separator in Python
Repeats a string a given number of times, joining the repetitions with an optional separator, with a guard for non-positive counts.
def repeat_string_with_separator(s, n, sep=''):
"""
Repeats a string n times, joining with a separator.
Args:
s (str): The string to repeat.
n (int): Number of repetitions.
sep (str): Separator between repetitions (default: '').
Returns:
str: The repeated strin…
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.
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…
Extract Data by Type from a List in Python: Numbers and Strings
Loop through a mixed list to filter out numeric and string values into separate lists.
def extract_numbers(items):
"""Extract all numeric values from a mixed list."""
numbers = []
for item in items:
if isinstance(item, (int, float)) and not isinstance(item, bool):
numbers.append(item)
return numbers
def extract_strings(items):
"""Extract all string values from a…
Format Lists of Tuples into Numbered Lines in Python
This code loops through a list of (name, grade) tuples and formats each into a numbered line using enumerate and f-strings.
def format_students(students):
formatted = []
for i, student in enumerate(students, start=1):
name, grade = student
formatted.append(f"{i}. {name}: {grade}")
return "\n".join(formatted)
if __name__ == "__main__":
students = [
("Alice", 92),
("Bob", 85),
("Charl…
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.
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…
How to Convert Data Types in Python Lists
Convert a mixed list of values to integers, floats, or strings based on their content, with graceful fallback for unparseable strings.
def convert_data(data):
"""Convert a mixed list of values to strings, ints, and floats."""
result = []
for item in data:
if isinstance(item, (int, float)):
result.append(str(item))
elif isinstance(item, str):
try:
if '.' in item:
r…
How to Filter Empty Strings in Python
Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.
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…
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.
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…
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.
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…
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.
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…
How to Safely Convert a List of Strings to Integers in Python
Convert a list of strings to integers while skipping invalid entries and collecting the failed values for inspection.
def safe_to_int(values):
"""Safely convert a list of strings to integers, skipping invalid entries."""
result = []
errors = []
for value in values:
try:
result.append(int(value))
except (ValueError, TypeError):
errors.append(value)
return result, errors
if …
How to Document Python Functions with Google Style Docstrings
Document a Python function with a Google style docstring to describe arguments and return values clearly.
def calculate_rectangle_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle in meters.
width (float): The width of the rectangle in meters.
Returns:
float: The area of the rectangle in square meters.
…
How to Use Default Parameters with Python's Split Function
Create a reusable Python wrapper around str.split with sensible default parameters for delimiter and maxsplit, showing beginners how default arguments work.
def split_with_defaults(text, delimiter=" ", maxsplit=-1):
"""
Split a string into parts using a delimiter.
Default behavior: split on spaces, unlimited splits.
"""
parts = text.split(delimiter, maxsplit)
return parts
if __name__ == "__main__":
# Example usage with defaults and custom par…
How to Use a Dispatch Table in Python (Map Strings to Functions)
Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b
dispatch = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide,
}
def…
How to Use a Lambda Sort Key in Python
Sort a list of strings by length, then alphabetically, using a lambda function as the sorting key in Python.
def sort_words(words):
"""Sort words by length, then alphabetically using a lambda key."""
return sorted(words, key=lambda word: (len(word), word))
if __name__ == "__main__":
sample_words = ["apple", "kiwi", "banana", "fig", "cherry"]
result = sort_words(sample_words)
print("Original:", sampl…
How to Use a Lambda Sorting Key in Python
Sort a list of strings by their last letter using a lambda function as the sorting key.
def get_last_letter(word):
return word[-1]
words = ["banana", "apple", "cherry", "date", "elderberry"]
if __name__ == "__main__":
sorted_words = sorted(words, key=get_last_letter)
print(sorted_words)
How to Use functools.reduce in Python
Apply functools.reduce with operator functions and lambda expressions to aggregate lists into sums, products, maximums, and concatenated strings.
from functools import reduce
import operator
# Sum all numbers in a list using reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(operator.add, numbers)
# Find the maximum value using reduce
max_result = reduce(lambda a, b: a if a > b else b, numbers)
# Multiply all numbers using reduce
product_result = reduce(la…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.