Strings & text
Format, split, join, parse, and clean text — everyday Python string patterns.
Build a Secure Password Strength Checker in Python
A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.
import re
def password_strength(password: str) -> str:
score = 0
if len(password) >= 8:
score += 1
if re.search(r'[a-z]', password):
score += 1
if re.search(r'[A-Z]', password):
score += 1
if re.search(r'\d', password):
score += 1
if re.search(r'[!@#$%^&*(),.?":…
Convert Natural Language Dates to Datetime in Python
Parse common natural language date phrases like 'tomorrow' or 'in 3 days' into Python datetime objects using regex and timedelta.
from datetime import datetime, timedelta
import re
def parse_natural_date(text: str) -> datetime:
"""Convert common natural language date expressions to datetime objects."""
now = datetime.now()
text = text.lower().strip()
# Handle relative dates
patterns = {
r"today": now,
r"…
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…
Extract URLs from text with regex in Python
Uses a regular expression to find and print HTTP/HTTPS URLs from a block of text.
import re
text = """
Visit https://www.example.com for docs.
Contact support@mysite.org.
Check http://localhost:8000/api or ftp://files.example.net.
"""
url_pattern = r'https?://[^\s]+'
urls = re.findall(url_pattern, text)
for url in urls:
print(url)
How to Convert camelCase to snake_case in Python
Convert camelCase strings to snake_case using a simple Python function that inserts underscores before uppercase letters and lowercases everything.
def camel_to_snake(s):
result = ""
for i, char in enumerate(s):
if char.isupper() and i > 0:
result += "_"
result += char.lower()
return result
if __name__ == "__main__":
test_cases = ["camelCase", "helloWorld", "thisIsACoolExample", "already_snake", "UPPER"]
for case i…
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 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 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 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…
Reverse Words in a Sentence While Keeping Punctuation in Python
Reverses the order of words in a sentence while leaving punctuation and spaces in their original positions using Python's re module.
def reverse_words_preserving_punctuation(sentence: str) -> str:
import re
# Split into words and punctuation tokens
tokens = re.findall(r'\w+|[^\w\s]|\s+', sentence)
words = [t for t in tokens if re.fullmatch(r'\w+', t)]
words.reverse()
result_parts = []
word_index = 0
for token in toke…
Validate email format with regex in Python
A Python function using a regex pattern to validate simple email formats, returning True or False for each input.
import re
def is_valid_email(email):
pattern = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'
return bool(re.match(pattern, email))
if __name__ == "__main__":
test_emails = [
"user@example.com",
"first.last@sub.domain.org",
"invalid-email",
"user@.com",
"user@…
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.