Reference library

Strings & text

Format, split, join, parse, and clean text — everyday Python string patterns.

7 matches
Strings & text easy

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.

regex string manipulation data cleaning
Python
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)
12 0 Open
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
Strings & text easy

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.

string punctuation translate
Python
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:…
14 0 Open
Strings & text easy

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.

strings case-insensitive substring
Python
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 <…
12 0 Open
Strings & text easy

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.

string-manipulation text-stats vowel-removal
Python
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…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Strings & text — Python code examples

What you will find here

This page collects strings & text snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.