Reference library

Python Code Samples

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

3 matches
Strings & text easy

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.

strings whitespace text-cleaning
Python
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:
     …
12 0 Open
Strings & text easy

How to Remove HTML Tags in Python with Regex

Strips all HTML tags from a string using a regular expression and cleans extra whitespace.

regex html text-cleaning
Python
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__ ==…
12 0 Open
Strings & text easy

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.

string whitespace text-cleaning
Python
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}'")
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.