String Operations - Working with Text

Strings (text) are like beads on a string. You can count them, cut the string at certain beads, add more beads, or replace some beads with others.
Strings are sequences of characters – letters, digits, symbols, spaces. In Python, strings are enclosed in single (`'`) or double (`"`) quotes. They are one of the most commonly used data types because almost every program deals with text: user input, file contents, API responses, messages, and more.

**Basic string operations:**

1. **Concatenation (`+`)** – Joins two or more strings together.
`"Hello" + " " + "World"` → `"Hello World"`

2. **Repetition (`*`)** – Repeats a string a given number of times.
`"Ha" * 3` → `"HaHaHa"`

3. **Length (`len()`)** – Returns the number of characters (including spaces).
`len("Python")` → `6`

4. **Indexing (`[]`)** – Accesses a single character by its position. Python uses zero‑based indexing (first character is index 0). Negative indices count from the end (`-1` is the last character).
Example: `text = "Python"`; `text[0]` → `'P'`; `text[-1]` → `'n'`

5. **Slicing (`[start:end:step]`)** – Extracts a substring.
- `text[1:4]` → characters from index 1 up to (but not including) 4 → `"yth"`
- `text[:3]` → first 3 characters → `"Pyt"`
- `text[3:]` → from index 3 to the end → `"hon"`
- `text[::2]` → every second character → `"Pto"`
- `text[::-1]` → reverses the string → `"nohtyP"`

**Common string methods:**
- `.upper()` – returns a new string with all uppercase letters.
- `.lower()` – returns a new string with all lowercase letters.
- `.capitalize()` – capitalizes the first character, lowercases the rest.
- `.title()` – capitalizes the first letter of each word.
- `.strip()` – removes leading/trailing whitespace (spaces, tabs, newlines).
- `.replace(old, new)` – replaces all occurrences of `old` with `new`.
- `.split(separator)` – splits the string into a list of substrings.
- `.join(iterable)` – joins elements of a list into a single string using the string as separator.
- `.find(substring)` – returns the index of the first occurrence (or `-1` if not found).
- `.count(substring)` – returns how many times `substring` appears.

**Checking string content:**
- `.isalpha()` – returns `True` if all characters are letters.
- `.isdigit()` – returns `True` if all characters are digits.
- `.isalnum()` – returns `True` if all characters are letters or digits.
- `.isspace()` – returns `True` if all characters are whitespace.

**Escape sequences (review from lesson 1):**
- `\n` – newline
- `\t` – tab
- `\\` – backslash
- `\'` – single quote inside a single‑quoted string
- `\"` – double quote inside a double‑quoted string

**String immutability:**
Strings in Python are *immutable* – you cannot change a character directly. Methods like `.upper()` return a *new* string; the original remains unchanged. To modify a string, you must assign the result to a variable.

**Common mistakes:**
- Trying to concatenate a string with a non‑string (e.g., `"Age: " + 25`) – you must convert the number with `str(25)`.
- Forgetting that indexing starts at `0`.
- Using `=` instead of `==` when comparing strings.
- Expecting `.replace()` to modify the original string (it returns a new one).

**Real‑world examples:**
- Cleaning user input with `.strip().lower()`.
- Building dynamic messages using concatenation or f‑strings.
- Parsing log files or CSV data with `.split()`.
- Validating password strength (length, digit/letter checks).
- Formatting names (e.g., `.title()` for proper case).

**Practice exercises:**
1. Create a string with your full name. Print its length and the first three characters.
2. Take a user‑input sentence and convert it to uppercase, then to lowercase.
3. Replace all spaces in a string with underscores using `.replace()`.
4. Extract the domain from an email address (everything after `@`).
5. Reverse a string using slicing (`[::-1]`).
# ========== EXAMPLE 1: Concatenation, Repetition, and Length ==========
print("=== Example 1: Basic String Operations ===")
first_name = "John"
last_name = "Doe"

# Concatenation
full_name = first_name + " " + last_name
print(f"Full name: {full_name}")

# Repetition
laugh = "ha"
laugh_3_times = laugh * 3
print(f"Laughter: {laugh_3_times}")

# Length
password = "mypassword123"
print(f"Password length: {len(password)} characters")
print()

# ========== EXAMPLE 2: Indexing, Slicing, and String Methods ==========
print("=== Example 2: Indexing, Slicing, and Methods ===")
text = "Python Programming"
print(f"Original: '{text}'")
print(f"First character: {text[0]}")
print(f"Last character: {text[-1]}")
print(f"First 6 characters: {text[:6]}")
print(f"From index 7: {text[7:]}")
print(f"Uppercase: {text.upper()}")
print(f"Lowercase: {text.lower()}")
print(f"Title case: {text.title()}")
print()

# ========== EXAMPLE 3: Searching, Replacing, and Splitting ==========
print("=== Example 3: Searching, Replacing, Splitting ===")
sentence = "  The quick brown fox jumps over the lazy dog.  "
print(f"Original: '{sentence}'")

# Strip whitespace
clean = sentence.strip()
print(f"After strip: '{clean}'")

# Find and replace
replaced = clean.replace("fox", "cat")
print(f"After replace: '{replaced}'")

# Find position
position = clean.find("brown")
print(f"'brown' starts at index: {position}")

# Split into words
words = clean.split()
print(f"Words list: {words}")
print(f"Number of words: {len(words)}")

# Join words with hyphen
hyphenated = "-".join(words)
print(f"Joined with hyphens: {hyphenated}")

→ Run this code interactively