Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
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 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 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 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:…
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 <…
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…
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.