Skip to main content

Learning outcomes

By the end of this chapter, you should be able to:
  • create and print strings
  • use indexing and slicing
  • apply basic string operators
  • explain string immutability

30-minute recording plan

  • 0-6 min: string creation and basics
  • 6-14 min: indexing and negative indexing
  • 14-22 min: slicing patterns and step
  • 22-27 min: operators on strings
  • 27-30 min: immutability and exam traps

Creating strings

s1 = "Python"
s2 = 'College'
Both single and double quotes are valid for normal strings.

Indexing

s = "Python"
print(s[0])   # P
print(s[-1])  # n
  • first index is 0
  • negative index counts from right side

Slicing

s = "Statistics"
print(s[0:5])   # Stati
print(s[5:])    # stics
print(s[:4])    # Stat
print(s[::2])   # Saiis
General form: text[start:end:step]

Beginner alert: slice end is excluded

In text[start:end], the end index is not included.
s = "Python"
print(s[0:2])  # Py (index 0 and 1 only)
print(s[0:6])  # Python

String operators

a = "Py"
b = "thon"
print(a + b)      # Python
print("ha" * 3)   # hahaha
Common operators:
  • + for concatenation
  • * for repetition
  • in for membership tests

Operator-function map (MCQ-critical)

  • + -> concatenates two strings
  • * -> repeats same string multiple times
  • [] -> accesses one character by index
  • [:] -> extracts slice/range
  • in -> membership check
  • \ -> escape character in string literal

Immutability

Strings cannot be changed in place.
s = "cat"
# s[0] = "b"  # TypeError
s = "b" + s[1:]
print(s)  # bat
Common confusion: strings look like lists of characters, but direct item assignment is not allowed.

Useful basics

text = "python"
print(len(text))
print("th" in text)

Advanced slicing trap (reverse-step puzzle)

With:
s = "abcdefghijklmnopqrstuvwxyz"
This combination prints zwtqnkheb on all 5 lines:
a, b, c, d, e = 1, 3, 25, 26, 0

print(s[-a:-len(s):-3])
print(s[::-b])
print(s[c:0:-3])
print(s[len(s):-d:-3])
print(s[:e:-3])
Why this works:
  • all 5 slices traverse from near z backward by step -3
  • each stop boundary is chosen so index 1 ('b') is last included char

Mini showcase: username cleanup

raw = "  Dhruv_2026  "
username = raw.strip().lower()

print(f"Raw: '{raw}'")
print(f"Clean username: '{username}'")
print(f"Starts with 'dh'? {username.startswith('dh')}")
This pattern appears in login forms and profile systems.

Exam-focused points

  • indexing starts at 0
  • negative index starts from end
  • slice end index is excluded
  • strings are immutable
  • know operator-function mapping for +, *, [], [:], in, \
  • for negative step slices, start/stop direction is reversed

Practice questions

  1. Take a word and print first and last character.
  2. Reverse a string using slicing.
  3. Print every alternate character from a string.
  4. Match these:
    • +, *, [], [:], in, \
    • concatenation, repetition, indexing, slicing, membership, escape