Python String Manipulation with f-strings and Regular Expressions
I parsed and reformatted text data using Python string methods, f-string formatting, and compiled regular expressions from the re module. Compiling patterns once and reusing them turned ad-hoc log parsing into a fast, reliable extraction routine.
Objective & Context
Most automation work is text wrangling. This lab covers slicing, str methods, f-string formatting with format specs, and regex capture groups, the toolkit behind log parsing and the sysadmin scripts lab.
Environment & Prerequisites
- Python 3.11 with the re module.
- Sample log lines to parse.
- A regex tester for pattern development.
flowchart LR
R[Raw line] --> C[re.compile pattern]
C --> M[match groups]
M --> F[f-string format]
F --> O[Structured output]
Step-by-Step Execution
1. Compile and apply a regex
import re
pat = re.compile(r"(\d+\.\d+\.\d+\.\d+).+?(\d{3})")
m = pat.search('203.0.113.5 - GET / 200')
ip, code = m.group(1), m.group(2)
2. Format with an f-string spec
python -c "ip='203.0.113.5'; code=200; print(f'{ip:>15} -> {code}')"3. Clean and split fields
python -c "print(' a,b,c '.strip().split(','))" 203.0.113.5 -> 200
['a', 'b', 'c']
Validation & Testing
Run the parser across a sample log and confirm every line extracts the IP and status code or is flagged as non-matching. Pass criteria: correct capture groups, aligned f-string output, and no unhandled exceptions on malformed lines.
Advanced: Troubleshooting
- Catastrophic backtracking: avoid nested quantifiers; anchor patterns.
- None on no match: guard
searchresults before accessing groups. - Slow repeated regex: compile once outside the loop.
Key Results
- Parsed structured fields from log lines with compiled regex.
- Reused one compiled pattern instead of recompiling per line.
- Produced aligned reports via f-string format specifiers.
- Handled malformed input without raising across the sample set.