Courses/Python Mastery/Module 3: Variables & Data Types
Module 3 · Lesson 330 minBeginner

Strings: Slicing, Methods, f-strings

Lesson goal
Master text: slice it, clean it, format it with f-strings.

Strings: Slicing, Methods, f-strings

Every name, message, URL, and password you'll ever process is a string. Python gives strings more built-in powers than any other type — this lesson makes you dangerous with them.

Creating strings

Quotes, single or double — both identical:

code
name = "Galvan"
name = 'Galvan'        # same thing
quote = "He said 'hi'" # doubles outside let you use singles inside

Joining and repeating

code
first = "Tech"
second = "With"
full = first + " " + second      # concatenation: Tech With
line = "-" * 20                  # --------------------
print(line)
print(full)
print(line)

+ joins strings; * repeats them. Both require *strings on both sides* — "Age: " + 21 crashes; "Age: " + str(21) works.

Indexing — every character has a number

code
word = "Python"
print(word[0])     # P   ← counting starts at 0
print(word[1])     # y
print(word[-1])    # n   ← negative counts from the END

The zero-counting trips everyone once. word[0] is the *first* character, and word[-1] is a shortcut for "the last one" that you'll use forever.

Slicing — cutting out pieces

The slice syntax is start:stop — and stop is excluded:

code
word = "Programming"
print(word[0:3])     # Pro   (positions 0,1,2 — 3 is NOT included)
print(word[3:7])     # gram
print(word[:3])      # Pro   (empty start = from the beginning)
print(word[3:])      # gramming (empty stop = to the end)
print(word[-3:])     # ming (last three)

The "stop is excluded" rule feels weird for a day, then becomes second nature — and its beauty is that word[0:3] has exactly 3 characters. The math always works.

f-strings — the modern way to build text

code
name = "Aarav"
score = 95

print(f"Student: {name}, Score: {score}")     # Student: Aarav, Score: 95
print(f"Next year: {score + 5}")              # expressions work inside!
print(f"Score: {score / 100:.0%}")            # formatting: 95%

Put f before the quotes, wrap variables in {}, and Python inserts their values — even calculations. This is *the* way to build display text in modern Python; you'll use it in every single project in this course.

String methods — the built-in toolbox

Strings carry their own functions (called methods — attached with a dot):

code
msg = "  Hello, World!  "

print(msg.strip())          # "Hello, World!"  — removes surrounding spaces
print(msg.upper())          # "  HELLO, WORLD!  "
print(msg.lower())          # "  hello, world!  "
print(msg.replace("World", "Python"))   # "  Hello, Python!  "
print(msg.count("l"))       # 3
print("hello".startswith("he"))   # True

Two crucial facts:

  • Methods return NEW stringsmsg.upper() does not change msg. To keep the result: msg = msg.upper().
  • Chaining worksmsg.strip().upper() runs left to right.
  • Checking what's inside

    code
    email = "galvan@tech.com"
    print("@" in email)              # True — the membership check
    print(email.index("@"))          # 6 — position of the first @
    print(len(email))                # 18 — total characters

    Common Errors & Fixes

  • `TypeError: can only concatenate str` — you added a string to a number. Convert: str(21) or use an f-string.
  • `IndexError: string index out of range` — you asked for position 10 in a 5-letter word. Remember: positions run 0 to len-1.
  • "My .upper() didn't work" — strings are immutable; methods return new strings. Capture the result: msg = msg.strip().

  • ✅ Checkpoint

  • What does "Python"[1] give? *(y — indexing starts at 0)*
  • What's word[0:3] of "Programming"? *(Pro — stop position excluded)*
  • How do you insert variables into text? *(f-strings: f"Hello {name}")*
  • Does msg.strip() change msg itself? *(No — it returns a new string; assign it to keep it)*
  • Next: booleans — the True/False type that powers every decision your code will ever make.