Python Strings
Data Types Focus
Python Strings
Strings store Unicode text. Master literals, methods, slicing, formatting, and encoding.
Literals
single = 'hello'
double = "hello"
multiline = """This spans lines"""
raw = r"C:\path\file"
Common methods
| Method | Description |
|---|---|
| strip() | Remove whitespace at both ends |
| lower() / upper() | Change case |
| replace(old, new) | Substitute text |
| split(delimiter) | Split into list |
| join(iterable) | Concatenate with delimiter |
| startswith()/endswith() | Prefix/suffix check |
Formatting
name = "Ada"
age = 32
f"{name} is {age}"
"{name} is {age}".format(name=name, age=age)
Prefer f-strings for readability and performance. Use format specifiers for numbers ({price:.2f}).
Encoding
- Strings are Unicode; encode to bytes with
.encode("utf-8"). - Decode bytes back to strings with
.decode("utf-8"). - Handle encoding errors explicitly (
errors="ignore"or"replace").