Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Strip Whitespace in Python
This code demonstrates how to remove leading and trailing whitespace from a string using the built-in strip() method.
def strip_whitespace(text: str) -> str:
return text.strip()
if __name__ == "__main__":
sample = " Hello, world! "
result = strip_whitespace(sample)
print(f"Original: '{sample}'")
print(f"Stripped: '{result}'")
How to Summarize Text Statistics in Python
This function returns basic statistics about a string, including character, word, and sentence counts, plus case and digit counts.
def summarize_text(text):
"""Return basic statistics about a string."""
words = text.split()
return {
"characters": len(text),
"words": len(words),
"sentences": text.count(".") + text.count("!") + text.count("?"),
"uppercase": sum(c.isupper() for c in text),
"lowerca…
How to Translate Characters in a String with str.maketrans in Python
Build and apply character translation tables with str.maketrans and str.translate to replace, delete, or remap letters in a Python string.
def translate_demo():
# Build a translation table: a→1, e→2, i→3, o→4, u→5
table = str.maketrans("aeiou", "12345")
text = "Hello, Python world! Keep coding, friend."
translated = text.translate(table)
print(f"Original: {text}")
print(f"Translated: {translated}")
# Example wit…
How to Use Template Strings for Substitution in Python
This code shows how to use Python's Template class for safe string substitution, replacing placeholders like $name with actual values.
from string import Template
def format_user_message(name, role, company):
template = Template("Hello $name! We are glad to have you as our $role at $company.")
return template.substitute(name=name, role=role, company=company)
if __name__ == "__main__":
result = format_user_message("Alice", "Python Develo…
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."""
…
How to remove punctuation from a string in Python
Remove all punctuation characters from a string using the str.translate method and string.punctuation from the standard library.
import string
def remove_punctuation(text: str) -> str:
return text.translate(str.maketrans("", "", string.punctuation))
if __name__ == "__main__":
sample = "Hello, world! It's a test... (with punctuation) - done?"
cleaned = remove_punctuation(sample)
print(f"Original: {sample}")
print(f"Cleaned:…
How to wrap long text to a specified width in Python
Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.
import textwrap
text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""
wrapped = textwrap.fill(text, width=40)
print(wrapped)
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: 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…
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.
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…
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.
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…
Validate email format with regex in Python
A Python function using a regex pattern to validate simple email formats, returning True or False for each input.
import re
def is_valid_email(email):
pattern = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'
return bool(re.match(pattern, email))
if __name__ == "__main__":
test_emails = [
"user@example.com",
"first.last@sub.domain.org",
"invalid-email",
"user@.com",
"user@…
Check if List is Sorted Ascending in Python
Verify that a list is sorted in ascending order using the all() function and a generator expression.
def is_sorted_ascending(lst):
return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))
if __name__ == "__main__":
test_lists = [
[1, 2, 3, 4, 5],
[1, 3, 2, 4, 5],
[5, 4, 3, 2, 1],
[1, 1, 2, 2, 3],
[10],
[]
]
for lst in test_lists:
print(f"{l…
Compare Two Lists in Python: Common, Only in First, Only in Second
A beginner-friendly helper that loops over two lists and returns items common to both, items only in the first list, and items only in the second list.
def compare_lists(list1, list2):
common = []
only_in_first = []
only_in_second = []
for item in list1:
if item in list2:
common.append(item)
else:
only_in_first.append(item)
for item in list2:
if item not in list1:
only_in_second…
Convert a List of Integers to a Comma-Separated String in Python
Convert a list of integers into a single comma-separated string using a generator expression and str.join.
def ints_to_comma_string(numbers):
return ",".join(str(num) for num in numbers)
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
result = ints_to_comma_string(numbers)
print(result)
Find All Occurrences of an Item in a Python List
Loop through a list with enumerate() to collect the index of every match for a target value.
def find_all(data, target):
"""Return indices of every occurrence of target in a list."""
indices = []
for index, item in enumerate(data):
if item == target:
indices.append(index)
return indices
if __name__ == "__main__":
sample = [10, 20, 30, 20, 40, 20, 50]
target_value …
Find Duplicate Elements in a Python List
Identifies and returns duplicate elements from a Python list using sets for efficient membership tests.
def find_duplicates(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return list(duplicates)
if __name__ == "__main__":
sample = [1, 2, 3, 2, 4, 1, 5, 3]
print(find_duplicates(sample))
Find Local Minima (Valleys) in a Numeric List in Python
This code finds indices of all local minima (valleys) in a numeric list, including edge cases, using a simple loop that compares each element with its neighbors.
def find_local_minima(numbers):
"""Find indices of local minima (valleys) in a numeric list.
A value is a local minimum if it's less than or equal to its neighbors.
Edge elements are considered minima if they're less than or equal to their single neighbor.
"""
if not numbers:
return []…
Find Maximum Value in a List of Numbers in Python
Iterate through a list with a for loop to manually find and return the maximum numeric value.
def find_max(numbers):
"""Return the maximum value in a list of numbers."""
if not numbers:
return None
max_value = numbers[0]
for num in numbers[1:]:
if num > max_value:
max_value = num
return max_value
if __name__ == "__main__":
sample_list = [3, 7, 2, 15, 9, 11]
…
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.