Python Strings π¶
Mentor's Note: Strings are more than just words; they are "chains" of individual characters. Think of them as a pearl necklaceβeach bead is a piece of data! π‘
π The Scenario: The Letter Train π¶
Imagine a long toy train where every carriage holds exactly one letter.
- The Logic: The whole train is the String. To find a specific letter, you look at the carriage number (The Index). π¦
- The Result: You can detach parts of the train (Slicing) or change the color of the paint (Methods). β
π Concept Explanation¶
1. Creating Strings¶
In Python, strings are surrounded by either single ' or double " quotes.
2. The Index Rule (Start from Zero!) π’¶
| V | i | s | h | n | u |
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
3. Slicing (Cutting the Train)¶
train[0:3]: Carriages 0 to 2 (Stops BEFORE the end index).train[2:]: From carriage 2 to the very end.
π¨ Visual Logic: Common Methods¶
graph LR
A["' hello '"] -- .strip() --> B["'hello'"]
B -- .upper() --> C["'HELLO'"]
C -- .lower() --> D["'hello'"]
D -- .replace('h', 'j') --> E["'jello'"]
π» Implementation: String Lab¶
# π Scenario: Formatting a User Profile
# π Action: Using slicing and f-strings
email = " [email protected] "
# 1. Clean the spaces π§Ή
clean_email = email.strip()
# 2. Get the domain (everything after @) βοΈ
domain = clean_email[7:]
# 3. Modern Formatting (f-strings) πͺ
user = "Vishnu"
welcome_msg = f"Welcome, {user}! Your domain is {domain}."
print(welcome_msg)
# ποΈ Outcome: "Welcome, Vishnu! Your domain is digital.com."
π Sample Dry Run (Slicing)¶
String: "Python"
| Instruction | Result | Why? |
|---|---|---|
s[0:2] |
"Py" |
Index 0 and 1. Stop at 2. βοΈ |
s[-1] |
"n" |
The very last character. |
s[::2] |
"Pto" |
Skip one carriage every time (Step). |
π Technical Analysis¶
- Immutability: Python strings are IMMUTABLE. You cannot change a carriage in an existing train. You must build a NEW train with the changes.
- Memory: Python optimizes memory by reusing common small strings (String Interning).
π― Practice Lab π§ͺ¶
Task: The Secret Decoder
Task: You have a string "ZYX-ABC". Use slicing to extract only the last 3 letters and print them in lowercase.
Hint: Use [-3:] and .lower(). π‘
π‘ Pro Tip: "Computers are good at following instructions, but not at reading your mind." - Donald Knuth