Python Strings: Immutable Text
A string (
str) is an immutable sequence of Unicode characters. This means you cannot change a string once it's created — you must create a new one.python
Creating Strings
python
Slicing Strings (Same as Lists!)
python
Essential String Methods
Python provides dozens of built-in methods for text manipulation.
| Method | Action | Example |
|---|---|---|
| .upper() | All caps | text.upper() |
| .lower() | All lowercase | text.lower() |
| .strip() | Remove whitespace | text.strip() |
| .split(sep) | Split into list | text.split(",") |
| .join(seq) | Join list into string | "-".join(["A", "B"]) |
| .replace(old, new) | Swap substrings | text.replace("A", "X") |
| .startswith(s) | Check beginning | text.startswith("A") |
| .endswith(s) | Check ending | text.endswith("a") |
| .find(s) | Get index of s | idx = text.find("B") |
python
Escape Sequences and Raw Strings
| Sequence | Character |
|---|---|
| \n | Newline |
| \t | Tab |
| \\ | Backslash |
| \' | Single quote |
| \" | Double quote |
Raw Strings (
r""): Useful for Windows paths and Regular Expressions where you don't want backslashes to be interpreted as escape sequences.python
Unicode and Encoding
Python 3 strings are Unicode by default. This means they handle non-ASCII characters (like emojis or foreign languages) seamlessly.
python
Regular Expressions (re)
For complex pattern matching, use the built-in
re module.python
Summary
| Feature | Method / Syntax |
|---|---|
| Immutability | Cannot be changed in-place |
| Transform | .strip(), .upper(), .lower() |
| Split/Join | .split(), .join() |
| Search | .find(), .startswith(), in msg |
| Regex | import re module |
| Unicode | Handled natively (UTF-8 default) |
| Best For | Human-readable text, parsing logs |