DAY-4 OF LEARNING PYTHON

 Yo, Day 4, let’s get stringy! 🎉

Heyy, you’re on a roll! Day 1 (Hello World), Day 2 (variables), and Day 3 (operators) are done, and now we’re at Day 4: Strings — the fun world of text in Python. Strings are super versatile — think names, messages, or even passwords. Today, we’ll learn to slice, dice, and manipulate them like a pro. This is a 1–2 hour hands-on session, written like we’re coding together over coffee. Fire up VS Code, make a day4.py file, and let’s dive in. Got stuck? Ping me!


Step 1: What Are Strings? (10 mins)

Strings are text — anything in quotes ("..." or '...'). Examples:

python
name = "Middle Class Blogs"
message = 'Hello, Python!'

Key Points:

  • Single (') or double (") quotes work the same.
  • Strings are immutable (you can’t change them directly, but you can make new ones).
  • Use len() to get length: len("Hello") → 5.
  • Strings are like a list of characters, so you can access them by index.

Action: Skim this for 5 mins → RealPython: Strings. Focus on “String Basics” and “Indexing”.


Step 2: String Indexing & Slicing (15 mins)

Each character in a string has an index (starts at 0):

text
"H e l l o"
 0 1 2 3 4

Indexing:

python
text = "Python"
print(text[0])  # P
print(text[5])  # n
print(text[-1]) # n (negative index, counts from end)

Slicing: Grab a chunk with [start:end:step].

python
print(text[0:3])  # Pyt (up to, but not including, index 3)
print(text[2:])   # thon (from index 2 to end)
print(text[::-1])  # nohtyP (reverse, step = -1)

Try This: In day4.py:

python
word = "Hello, World!"
print(word[0])      # H
print(word[0:5])    # Hello
print(word[-6:])    # World!
print(word[::-1])   # !dlroW ,olleH

Run it (python day4.py) and play with different slices (e.g., word[2:8]).


Step 3: String Methods (20 mins)

Python strings come with built-in methods to manipulate them. Here are the must-know ones:

MethodWhat it doesExample
.upper() All uppercase"hi".upper() → "HI"
.lower()All lowercase"HI".lower() → "hi"
.strip()Remove leading/trailing spaces" hello ".strip() → "hello"
.replace(old, new)Replace text"cat".replace("c", "h") → "hat"
.split(sep)Split into list"a,b,c".split(",") → ["a", "b", "c"]
.join(list)Join list into string" ".join(["hi", "there"]) → "hi there"

Code It:

python
text = "  Welcome to Python!  "
print(text.upper())          # WELCOME TO PYTHON!
print(text.lower())          # welcome to python!
print(text.strip())          # Welcome to Python!
print(text.replace("Python", "Coding"))  # Welcome to Coding!
print(text.split())          # ['Welcome', 'to', 'Python!']
print("-".join(["a", "b", "c"]))  # a-b-c

Pro Tip: Methods don’t change the original string (immutable!). They return a new string.

Try This: Add to day4.py:

python
sentence = "I love coding in Python"
print(sentence.split(" "))  # Split by space
print(sentence.replace("Python", "Java"))

Output:

text
['I', 'love', 'coding', 'in', 'Python']
I love coding in Java

Step 4: Mini Project — String Manipulator (30–40 mins)

Let’s build a String Manipulator! It’ll:

  1. Ask user for a sentence.
  2. Print:
    • Length of the sentence.
    • Sentence in uppercase.
    • First 5 characters.
    • Check if “Python” is in the sentence.
    • Reverse the sentence.

Code (day4_manipulator.py):

day4_manipulator.py
python

Run It:

text
Enter a sentence: I love Python coding
Length: 19
Uppercase: I LOVE PYTHON CODING
First 5 chars: I lov
Has 'Python'? True
Reversed: gnidoc nohtyP evol I

Challenge: Add error handling for empty input:

python
sentence = input("Enter a sentence: ")
if not sentence.strip():
    print("Error: Enter something!")
else:
    print("Length:", len(sentence))
    # ... rest of code

Extra Fun: Count words using len(sentence.split()).


Step 5: Common Mistakes & Fixes (5 mins)

ErrorWhy?Fix
IndexErrortext[100] (beyond length)Check len(text)
TypeErrortext + 5Convert non-string: text + str(5)
No outputForgot quotes"hello", not hello


Day 4 Wrap-Up

You nailed:

  • String indexing (text[0]) and slicing (text[1:4])
  • Methods like .upper(), .split(), .replace()
  • Built a String Manipulator
  • Used in operator and len()

Track Progress (in a notebook):

Day 4 Done: Strings are awesome! Sliced text and built a manipulator. Doubt: Why can’t I change text[0] = "X"? Answer: Strings are immutable — create a new string instead (e.g., text = "X" + text[1:]).

Resources:


Tomorrow: Day 5 — Lists

We’ll mess with lists (like arrays but cooler):

python
fruits = ["apple", "banana", "orange"]
print(fruits[1])  # banana

Prep: Peek at W3Schools: Python Lists.


FOLLOW OUR WHATSAPP CHANNEL:

MIDDLE CLASS BLOGS

Comments

Popular Posts