Strings & Text Processing Mechanics
An authoritative reference manual on string immutability, PyUnicodeObject structure, UTF-8/UTF-16 encoding, string interning, dual indexing, slicing math [start:stop:step], string methods, f-strings, character/word analytics, and substring insertion.
Strings are immutable sequences of Unicode characters representing text data in Python. This chapter covers CPython `PyUnicodeObject` memory allocation, string interning, indexing, slicing mechanics, built-in string functions, formatting methods, and text parsing algorithms.
3.1. 1. String Creation, Immutability & Slicing Mechanics
Definition: Strings in Python are immutable sequence objects backed by the `PyUnicodeObject` structure; modifying string content allocates a new string object in heap memory.
Core Working Principles:
- String Creation & Immutability Rationale: Enclosed in single (`'`), double (`"`), or triple (`"""`) quotes. Python performs **String Interning** (reusing immutable string literals in memory to optimize RAM and enable fast pointer comparisons). Immutability guarantees thread-safety and constant hash keys.
- Dual Indexing System:
- • Positive Indexing: `0` to `N-1` (left-to-right).
- • Negative Indexing: `-1` to `-N` (right-to-left).
- Mathematical Slicing Formula: `string[start:stop:step]`. Extracts characters from `start` index up to `stop-1` index using `step` stride. Python automatically clamps out-of-bound slice indices. Reversing string: `string[::-1]`.
graph LR
subgraph PosIndex[Positive Memory Offsets]
P0[0: 'P'] --- P1[1: 'y'] --- P2[2: 't'] --- P3[3: 'h'] --- P4[4: 'o'] --- P5[5: 'n']
end
subgraph NegIndex[Negative Memory Offsets]
N0[-6: 'P'] --- N1[-5: 'y'] --- N2[-4: 't'] --- N3[-3: 'h'] --- N4[-2: 'o'] --- N5[-1: 'n']
end
5-Marks Exam Scoring Points
- Strings are immutable; modifying string characters raises TypeError.
- Slicing string[start:stop:step] extracts substrings safely without IndexErrors.
- Negative step [::-1] reverses string sequence.
3.2. 2. String Methods, Formatting & Substring Insertion
Definition: Python provides built-in methods for text manipulation, string formatting, word counting, and substring insertion.
Core Working Principles:
- Essential String Methods: `lower()`, `upper()`, `strip()` (removes leading/trailing whitespace), `split(sep)` (splits string into list), `join(seq)` (joins sequence into string), `find(sub)` (returns index or -1), `replace(old, new)`, `startswith()`, `endswith()`.
- Formatting Performance Comparison:
- • f-Strings (Python 3.6+ Standard): `f"Result: {val:.2f}"`. Evaluated at runtime via compiled bytecode instructions (Fastest!).
- • `str.format()`: `"Result: {:.2f}".format(val)`.
- • `%` Formatting: `"Result: %.2f" % val`.
- Word & Character Analytics: Counting characters (`len(text)`), counting words (`len(text.split())`), and inserting substrings via slicing (`text[:idx] + insert_str + text[idx:]`). Time complexity of string concatenation `+` ($O(N^2)$) vs `str.join()` ($O(N)$ single memory allocation).
raw_text = " The Quick Brown Fox Jumps Over The Lazy Dog "
# 1. Text Cleaning & Splitting
cleaned = raw_text.strip()
words_list = cleaned.split()
word_count = len(words_list)
char_count = len(cleaned)
# 2. Substring Insertion at index 10
target_idx = 10
inserted_text = cleaned[:target_idx] + "[PYTHON_INSERT] " + cleaned[target_idx:]
# 3. String Formatting
print(f"Cleaned Text: '{cleaned}'")
print(f"Word Count: {word_count} | Character Count: {char_count}")
print(f"Inserted Result: {inserted_text}")
5-Marks Exam Scoring Points
- f-strings offer optimal execution performance and readable syntax.
- str.split() parses text into lists based on whitespace delimiters.
- Substrings are inserted by concatenating left slice, insert string, and right slice.
✍️ Chapter 3 Reference Exercises & Review Problems
def text_analyzer(text, insert_str, index):
cleaned = text.strip()
total_chars = len(cleaned)
total_words = len(cleaned.split())
reversed_str = cleaned[::-1]
# Substring insertion via slicing
inserted_str = cleaned[:index] + insert_str + cleaned[index:]
return total_chars, total_words, reversed_str, inserted_str
# Test invocation
c, w, rev, ins = text_analyzer("Python is amazing", "VERY ", 10)
print(f"Chars: {c}, Words: {w}\nReversed: {rev}\nInserted: {ins}")
- **Concatenation with `+` in a Loop:** Because strings are immutable, executing `s += word` inside a loop creates a brand-new string object and copies memory on *every single iteration* ($O(N^2)$ time complexity overhead!).
- **`str.join()` Method:** Pre-calculates the exact total memory required for all elements combined, allocates a single memory buffer once, and copies all strings in C ($O(N)$ linear time efficiency!).