Strings as Structures
Treat strings like sequences: indexing, slicing, iteration, and why immutability matters when you build text processing and parsing logic.
A string is also a **sequence data structure**. Key idea: - string is **ordered** - string is **immutable** - you can index and slice it like lists/tuples ## Indexing and slicing ```python s = "Python" print(s[0]) # P print(s[-1]) # n print(s[1:4]) # yth ``` ## Looping ```python for ch in "abc": print(ch) ``` ## Why immutability matters You cannot modify a character directly: ```python s = "cat" # s[0] = "b" # error ``` Instead, you create a new string: ```python s = "b" + s[1:] print(s) # bat ``` ## Common beginner need: building strings efficiently If you are joining many parts: ```python parts = ["Hello", "from", "Python"] result = " ".join(parts) print(result) ``` ## Graph: string immutability ```mermaid flowchart LR A[Old string] --> B[Cannot change in place] B --> C[Create new string] ``` ## Remember - strings behave like sequences - immutable means safe but you must rebuild for changes - join() is best for combining many parts