python
message = f"Hello, {name}!"String handling, file I/O, pathlib, JSON, and exception-handling patterns.
Common string formatting and parsing patterns.
message = f"Hello, {name}!"label = f"{total:,}"parts = [part.strip() for part in csv_line.split(",")]path = "/".join(["api", "v1", "users"])cleaned = text.replace("\t", " ")if filename.endswith(".py") and filename.startswith("test_"):
print("test file")normalized = line.strip()Working with text files and pathlib.
with open("notes.txt", "r", encoding="utf-8") as f:
text = f.read()with open("app.log", "r", encoding="utf-8") as f:
for line in f:
print(line.rstrip())with open("output.txt", "w", encoding="utf-8") as f:
f.write("hello
")with open("events.log", "a", encoding="utf-8") as f:
f.write("started
")from pathlib import Path
path = Path("src") / "main.py"
exists = path.exists()import json
from pathlib import Path
data = json.loads(Path("config.json").read_text(encoding="utf-8"))Error handling patterns from the tutorial and language reference.
try:
value = int(user_input)
except ValueError:
value = 0try:
data = json.loads(payload)
except (TypeError, ValueError) as exc:
print(exc)try:
result = risky()
except Exception as exc:
logger.error(exc)
else:
print(result)
finally:
cleanup()raise ValueError("expected a positive integer")try:
parse_config(path)
except OSError as exc:
raise RuntimeError("config load failed") from excclass ConfigError(Exception):
pass