Master professional Python: regex, context managers, and asynchronous programming.
Industry-level techniques for text processing, resource management, and concurrent code.
re module.import re
# Search for a pattern
text = "My phone is 123-456-7890"
match = re.search(r'\d{3}-\d{3}-\d{4}', text)
if match:
print(match.group()) # 123-456-7890\d - digit [0-9]
\w - word char [a-zA-Z0-9_]
\s - whitespace
. - any character
* - 0 or more
+ - 1 or more
? - 0 or 1
{n} - exactly n times
[] - character class
^ - start of string
$ - end of stringtext = "Email me at john@example.com or jane@test.org"
emails = re.findall(r'\w+@\w+\.\w+', text)
print(emails) # ['john@example.com', 'jane@test.org']text = "Hello World"
result = re.sub(r'World', 'Python', text)
print(result) # Hello Pythonr'pattern' to avoid escape issuesre.compile() for reusable patterns(): match.group(1)Phone: 123-456-7890
Emails: ['john@example.com', 'jane@test.org']
Replaced: Hello Python
import rere.search(r'pattern', text)re.findall(r'pattern', text)re.sub(r'old', 'new', text)\d+ Words: \w+Review feedback below
with statements and creating custom context managers.# with automatically closes the file, even if errors occur
with open('file.txt', 'w') as f:
f.write('Hello, World!')
# File is automatically closed here
with open('file.txt', 'r') as f:
content = f.read()
print(content)class Timer:
def __enter__(self):
import time
self.start = time.time()
print("Timer started")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
elapsed = time.time() - self.start
print(f"Elapsed: {elapsed:.4f} seconds")
return False # Don't suppress exceptions
with Timer() as t:
# Code to time
sum(range(1000000))from contextlib import contextmanager
@contextmanager
def managed_resource(name):
print(f"Acquiring {name}")
try:
yield name # Value returned to 'as' variable
finally:
print(f"Releasing {name}")
with managed_resource("database") as r:
print(f"Using {r}")__enter__ runs at start of with block__exit__ runs at end (even if exception)False from __exit__ to propagate exceptionsTimer started
Processing...
Elapsed: 0.0234 seconds
Acquiring database
Using database
Releasing database
__enter__(self) and __exit__(self, ...)exc_type, exc_val, exc_tbwith MyContext() as ctx:@contextmanager with yieldReview feedback below
async/await for concurrent, non-blocking code execution.import asyncio
async def greet(name):
print(f"Hello, {name}!")
await asyncio.sleep(1) # Non-blocking sleep
print(f"Goodbye, {name}!")
# Run async function
asyncio.run(greet("Alice"))async def fetch_data(id, delay):
print(f"Fetching data {id}...")
await asyncio.sleep(delay)
print(f"Data {id} ready!")
return f"Result {id}"
async def main():
# Run tasks concurrently with gather
results = await asyncio.gather(
fetch_data(1, 2),
fetch_data(2, 1),
fetch_data(3, 1.5)
)
print("All results:", results)
asyncio.run(main())async def main():
task1 = asyncio.create_task(fetch_data(1, 2))
task2 = asyncio.create_task(fetch_data(2, 1))
# Wait for both
result1 = await task1
result2 = await task2
print(result1, result2)async def defines a coroutineawait pauses until the awaited task completesasyncio.gather() runs multiple coroutines concurrentlyFetching data 1...
Fetching data 2...
Fetching data 3...
Data 2 ready!
Data 3 ready!
Data 1 ready!
All results: ['Result 1', 'Result 2', 'Result 3']
import asyncioasync def func():await asyncio.sleep(1)asyncio.run(main())await asyncio.gather(task1, task2)Review feedback below