Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
Automatically Detect Weak Passwords from Large Password Lists in Python
This Python script identifies weak passwords from a list by checking length, common patterns, sequential characters, and uniform characters, returning those that fail the security checks.
import re
COMMON_PASSWORDS_FILE = "common_passwords.txt"
def is_weak(password):
# Check length
if len(password) < 8:
return True
# Check for common patterns
if password.lower() in {"password", "123456", "qwerty", "letmein", "admin", "welcome"}:
return True
# Check for sequential c…
Extract Email-Like Tokens from Text in Python
Uses a regular expression to find all email-like tokens in a string, returning them as a list with re.findall.
import re
def extract_email_like_tokens(text):
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'
return re.findall(pattern, text)
if __name__ == "__main__":
sample_text = (
"Contact us at support@example.com or sales@company.co.uk. "
"Invalid: hello@world, user@.com, test@do…
How to Build a Basic Text Processor in Python
Split text into sentences, count words, find the longest word, and convert text to uppercase — all with pure Python string methods.
text = """The quick brown fox jumps over the lazy dog.
Python is a powerful programming language.
Keep practicing every single day!"""
sentences = text.split(". ")
word_count = 0
longest_word = ""
for sentence in sentences:
words = sentence.split()
word_count += len(words)
for word in words:
clea…
How to Check Palindrome in Python (Ignore Case and Spaces)
Check whether a string is a palindrome while ignoring case, spaces, and all non-alphanumeric characters using Python's filter and string reversal.
def is_palindrome(text: str) -> bool:
cleaned = ''.join(char.lower() for char in text if char.isalnum())
return cleaned == cleaned[::-1]
if __name__ == "__main__":
test_cases = [
"A man, a plan, a canal: Panama",
"race a car",
"Was it a car or a cat I saw?",
"hello",
…
How to Detect PII in Documents Using Python
Use regex patterns to automatically detect emails, phone numbers, SSNs, and credit card numbers in text documents.
import re
from typing import List, Dict
def detect_pii(text: str) -> Dict[str, List[str]]:
patterns = {
"email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
"phone": r"\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
"ssn": r"\b\d{3}-\d{2}-\d{4}\b",
"credit_card": r"\b\d{4}[- ]?\d{4}[-…
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 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 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 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 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:…
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.