Substitution Methods
Basic Substitution Techniques
Regular expression substitution allows you to replace text patterns efficiently using Python's re
module.
Key Substitution Methods
Method |
Description |
Use Case |
re.sub() |
Replace all occurrences |
General text transformation |
re.subn() |
Replace with count of replacements |
Tracking modifications |
Simple Substitution Example
import re
## Basic string replacement
text = "Hello, LabEx is awesome programming platform"
result = re.sub(r"LabEx", "Python Learning", text)
print(result)
## Output: Hello, Python Learning is awesome programming platform
Multiple Substitutions
def multiple_replacements(text):
## Define replacement dictionary
replacements = {
r'\bpython\b': 'Python',
r'\blinux\b': 'Linux',
r'\bregex\b': 'Regular Expression'
}
## Apply replacements
for pattern, replacement in replacements.items():
text = re.sub(pattern, replacement, text, flags=re.IGNORECASE)
return text
sample_text = "python is great for linux regex programming"
transformed_text = multiple_replacements(sample_text)
print(transformed_text)
Advanced Substitution Techniques
def transform_with_callback(text):
def capitalize_match(match):
return match.group(0).upper()
pattern = r'\b\w{3,}\b'
return re.sub(pattern, capitalize_match, text)
text = "LabEx provides excellent coding tutorials"
result = transform_with_callback(text)
print(result)
Substitution Workflow
graph TD
A[Original Text] --> B[Regex Pattern]
B --> C{Pattern Match?}
C --> |Yes| D[Replace Text]
C --> |No| E[Keep Original]
D --> F[Updated Text]
- Use raw strings for patterns
- Compile regex for repeated use
- Be specific with patterns
- Consider performance with large texts
Common Substitution Scenarios
- Data cleaning
- Text normalization
- Log file processing
- Configuration file modifications
By mastering these substitution techniques, you'll enhance your text manipulation skills in Python, making complex transformations straightforward and efficient.