Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Escape HTML in Python
This code demonstrates how to use Python's `html.escape` function to safely encode user input for display in HTML, preventing XSS attacks.
import html
def escape_user_input(user_input: str) -> str:
"""Escape HTML-sensitive characters for safe display."""
return html.escape(user_input)
if __name__ == "__main__":
sample_user_input = '<script>alert("XSS")</script> & \'quotes\''
safe_output = escape_user_input(sample_user_input)
print("…
How to Extract Digits Only from a String in Python
This code uses a regular expression to remove all non-digit characters from a mixed string, returning only the digits.
import re
def extract_digits(text):
"""Return only the digits from the given text as a string."""
return re.sub(r'\D', '', text)
if __name__ == "__main__":
mixed = "abc123def456!@#789"
result = extract_digits(mixed)
print(result)
How to Filter Text to Only Letters, Numbers, and Spaces in Python
A beginner-friendly function that filters a string to keep only alphabetic characters, digits, and spaces, removing punctuation and symbols.
def filter_text(text, keep_alpha=True, keep_digits=True, keep_spaces=True):
allowed = set()
if keep_alpha:
allowed.update("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
if keep_digits:
allowed.update("0123456789")
if keep_spaces:
allowed.add(" ")
return "".join(ch f…
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.
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:"…
How to Format a Float as Currency in Python
This code defines a function that converts a float to a string formatted as US currency with two decimal places and comma separators.
def format_currency(amount):
return f"${amount:,.2f}"
if __name__ == "__main__":
test_amounts = [1234.5, 0, 9999999.999, -42.867]
for amount in test_amounts:
print(f"{amount} -> {format_currency(amount)}")
How to Generate Text Helper Functions in Python
Three simple Python functions that repeat, join, and count characters in strings for beginners.
def repeat_text(text, times):
"""Repeat a string a given number of times."""
return text * times
def join_words(words, separator=" "):
"""Join a list of words into a single string."""
return separator.join(words)
def count_characters(text):
"""Count character occurrences in a string."""
ret…
How to Group Data by Category in Python
Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.
def group_by_category(data):
"""Group list of (category, value) tuples into dictionaries of lists."""
groups = {}
for category, value in data:
groups.setdefault(category, []).append(value)
return groups
if __name__ == "__main__":
items = [
("fruit", "apple"),
("veg", "carro…
How to Highlight Search Terms in Python Text
Highlights all case-insensitive occurrences of a search term in a string by wrapping them in markers.
def highlight_search_term(text: str, term: str) -> str:
"""Highlight all occurrences of term in text using terminal-style markers."""
if not term:
return text
term_lower = term.lower()
result = []
i = 0
while i < len(text):
# Check if the term starts at position i (case-insens…
How to Inspect String Statistics in Python
A beginner-friendly function that returns detailed statistics about a string, including length, word count, character types, and easy text transformations.
def inspect_text(text: str) -> dict:
"""Return useful stats about a string for beginners."""
words = text.split()
return {
"length": len(text),
"word_count": len(words),
"uppercase": sum(1 for ch in text if ch.isupper()),
"lowercase": sum(1 for ch in text if ch.islower()),
…
How to Mask Credit Card Middle Digits in Python
Mask the middle digits of credit card numbers in a string, keeping only the first 8 and last 4 digits, using regular expressions.
import re
def mask_credit_card(text: str) -> str:
pattern = re.compile(r'(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4})')
return pattern.sub(lambda m: m.group(1) + m.group(2) + '****' + m.group(4), text)
if __name__ == "__main__":
sample = "Card: 1234-5678-9012-3456 and 1111 2222 3333 4444"
print(mas…
How to Normalize Text in Python
This code defines a function that trims, lowercases, and collapses extra whitespace in a string, returning normalized text.
def normalize_text(text: str) -> str:
normalized = " ".join(text.lower().strip().split())
return normalized
if __name__ == "__main__":
raw = " Hello, WORLD! This is a test. "
print(normalize_text(raw))
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.
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…
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.
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…
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.
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…
How to Remove Duplicate Adjacent Spaces in Python
This Python function collapses any sequence of two or more adjacent spaces into a single space, preserving all other characters.
def remove_duplicate_adjacent_spaces(text):
"""Replace sequences of 2+ spaces with a single space."""
result = []
prev_was_space = False
for char in text:
if char == " ":
if not prev_was_space:
result.append(char)
prev_was_space = True
else:
…
How to Remove HTML Tags in Python with Regex
Strips all HTML tags from a string using a regular expression and cleans extra whitespace.
import re
def remove_html_tags(text: str) -> str:
"""Remove all HTML tags from the given text using regex."""
# Remove opening and closing tags
clean = re.sub(r'<[^>]+>', '', text)
# Remove any extra whitespace left behind
clean = re.sub(r'\s+', ' ', clean).strip()
return clean
if __name__ ==…
How to Replace Multiple Spaces with a Single Space in Python
This snippet uses the `re` module to collapse runs of consecutive spaces in a string into a single space, cleaning up whitespace.
import re
def collapse_spaces(text):
"""Replace multiple consecutive spaces with a single space."""
return re.sub(r' +', ' ', text)
if __name__ == "__main__":
sample = "This has multiple spaces between words."
result = collapse_spaces(sample)
print(f"Original: '{sample}'")
print(f"Co…
How to Round Numbers with f-strings in Python
Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.
def main():
# Values to format with expression-based rounding
price = 19.995
tax_rate = 0.0825
distance = 1234.56789
# Round inside the f-string expression using round()
print(f"Price rounded to cents: ${round(price, 2)}")
# Combine rounding with arithmetic inside the expression
total…
How to Slugify a String in Python
Convert any text into a URL-friendly slug using the standard library's unicodedata and re modules.
import re
import unicodedata
def slugify(text):
text = unicodedata.normalize('NFKD', text)
text = text.encode('ascii', 'ignore').decode('ascii')
text = re.sub(r'[^\w\s-]', '', text).strip().lower()
text = re.sub(r'[-\s]+', '-', text)
return text
if __name__ == "__main__":
title = "Hello, Worl…
How to Sort Text Alphabetically in Python
Sort words or lines alphabetically with case-insensitive ordering while preserving original casing.
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(…
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.
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__":
…
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.
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(…
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.
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…
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.
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)}")
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.