Detailed Guide to Python String Processing with the re and string Modules
This article explains how to use Python's re and string modules for common string tasks such as pattern searching, substitution, splitting, and character checks, providing clear explanations and ten practical code examples.
In Python programming, handling strings is a frequent task; this guide introduces two essential modules— re for regular expressions and string for predefined character sets—to perform matching, replacement, splitting, and validation operations.
re module
The re module offers powerful tools for text pattern matching and substitution.
Example 1: Search pattern
import re
# Search pattern
text = "Hello, my number is 123-456-7890."
pattern = r"\d{3}-\d{3}-\d{4}"
match = re.search(pattern, text)
print("Found pattern:", match.group() if match else "No match found.")Example 2: Replace pattern
import re
# Replace pattern
text = "Hello, my number is 123-456-7890."
new_text = re.sub(r"\d{3}-\d{3}-\d{4}", "[REDACTED]", text)
print("New text:", new_text)Example 3: Find all matches
import re
# Find all matches
text = "My numbers are 123-456-7890 and 098-765-4321."
pattern = r"\d{3}-\d{3}-\d{4}"
matches = re.findall(pattern, text)
print("Found matches:", matches)Example 4: Split string
import re
# Split string
text = "one,two,three;four,five;six"
pattern = r"[,;]"
split_text = re.split(pattern, text)
print("Split text:", split_text)Example 5: Replace all matches using a function
import re
# Replace all matches (using function)
def redact(match):
return "[REDACTED]"
text = "My numbers are 123-456-7890 and 098-765-4321."
pattern = r"\d{3}-\d{3}-\d{4}"
new_text = re.sub(pattern, redact, text)
print("New text:", new_text)string module
The string module provides a collection of useful constants such as whitespace characters, letters, and digits.
Example 6: Use constants
import string
# Use constants
print("ASCII lowercase letters:", string.ascii_lowercase)
print("ASCII uppercase letters:", string.ascii_uppercase)
print("Digits:", string.digits)Example 7: Generate a random password
import string
import random
# Generate random password
def generate_password(length=10):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
return password
password = generate_password()
print("Generated password:", password)Example 8: Remove whitespace characters
import string
# Remove whitespace characters
text = "Hello, world!"
cleaned_text = text.translate(str.maketrans("", "", string.whitespace))
print("Cleaned text:", cleaned_text)Example 9: Check if a string contains only digits
import string
# Check if a string contains only digits
text = "1234567890"
if all(char in string.digits for char in text):
print(f"'{text}' contains only digits.")
else:
print(f"'{text}' does not contain only digits.")Example 10: Check if a string contains only letters
import string
# Check if a string contains only letters
text = "HelloWorld"
if all(char in string.ascii_letters for char in text):
print(f"'{text}' contains only letters.")
else:
print(f"'{text}' does not contain only letters.")Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.