Python Strings, Files, and Exceptions

String handling, file I/O, pathlib, JSON, and exception-handling patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Strings

Common string formatting and parsing patterns.

f-string interpolation

f-string interpolation

pythonANYstringsformatting
python
message = f"Hello, {name}!"

Format number with commas

Format number with commas

pythonANYstringsformatting
python
label = f"{total:,}"

Split and strip

Split and strip

pythonANYstringssplit
python
parts = [part.strip() for part in csv_line.split(",")]

Join strings

Join strings

pythonANYstringsjoin
python
path = "/".join(["api", "v1", "users"])

Replace text

Replace text

pythonANYstringsreplace
python
cleaned = text.replace("\t", "    ")

Prefix / suffix checks

Prefix / suffix checks

pythonANYstringsstartswithendswith
python
if filename.endswith(".py") and filename.startswith("test_"):
    print("test file")

Strip whitespace

Strip whitespace

pythonANYstringsstrip
python
normalized = line.strip()

Files and paths

Working with text files and pathlib.

Read a text file

Read a text file

pythonANYfilesread
python
with open("notes.txt", "r", encoding="utf-8") as f:
    text = f.read()

Read line by line

Read line by line

pythonANYfilesread
python
with open("app.log", "r", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())

Write a text file

Write a text file

pythonANYfileswrite
python
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("hello
")

Append to a file

Append to a file

pythonANYfilesappend
python
with open("events.log", "a", encoding="utf-8") as f:
    f.write("started
")

Use pathlib

Use pathlib

pythonANYpathlibfiles
python
from pathlib import Path
path = Path("src") / "main.py"
exists = path.exists()

Read JSON from disk

Read JSON from disk

pythonANYjsonpathlib
python
import json
from pathlib import Path
data = json.loads(Path("config.json").read_text(encoding="utf-8"))

Exceptions

Error handling patterns from the tutorial and language reference.

Basic try / except

Basic try / except

pythonANYexceptionstry
python
try:
    value = int(user_input)
except ValueError:
    value = 0

Catch multiple exceptions

Catch multiple exceptions

pythonANYexceptionsjson
python
try:
    data = json.loads(payload)
except (TypeError, ValueError) as exc:
    print(exc)

Else and finally

Else and finally

pythonANYexceptionsfinally
python
try:
    result = risky()
except Exception as exc:
    logger.error(exc)
else:
    print(result)
finally:
    cleanup()

Raise custom error

Raise custom error

pythonANYexceptionsraise
python
raise ValueError("expected a positive integer")

Exception chaining

Exception chaining

pythonANYexceptionsraise
python
try:
    parse_config(path)
except OSError as exc:
    raise RuntimeError("config load failed") from exc

Define custom exception

Define custom exception

pythonANYexceptionscustom
python
class ConfigError(Exception):
    pass