MOD-06 · Sequence #6 · Python Strings

Python Strings & Slicing

Python strings are immutable sequences of Unicode code points. Slicing with [start:stop:step], negative indices, built-in string transformation methods, and modern f-strings make string manipulation fast and expressive.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
s = "Hello, World!"
print(s[7:12])   # 'World'
print(s[::-1])   # Reverse string: '!dlroW ,olleH'

Core Principles & Mental Models

1. Slicing with [start:stop:step]

Half-Open Intervals & Negative Step Strides

  • String indexing starts at 0 for positive indices and -1 for the last character.
  • Slices use half-open intervals [start:stop): the element at stop is excluded.
  • A negative step reverses the direction of traversal: s[::-1] creates a reversed string.
  • Slicing never raises an IndexError; it gracefully clamps out-of-range indices.
text = "PythonLab"
print("First 4:", text[:4])       # 'Pyth'
print("Index 2 to 6:", text[2:6])  # 'thon'
print("Every 2nd char:", text[::2]) # 'PtoL'
print("Reversed:", text[::-1])     # 'baLnohtyP'
💡 Key Takeaway: The slice notation [start:stop:step] provides O(k) substring extraction where k is the slice length.

2. Formatted String Literals (f-strings)

Interpolation and Specifiers

  • Introduced in Python 3.6, f-strings (f"...") evaluate expressions inside curly braces {} at runtime.
  • They support formatting specifiers: :.2f for decimals, :>10 for right-align padding, :04d for zero-padded integers.
  • f-strings are significantly faster than % formatting and str.format() because expressions are parsed into optimized bytecode at compile time.
name = "Ada"
gpa = 3.9482
print(f"Student: {name:<8} | GPA: {gpa:.2f}")
💡 Key Takeaway: Always prefer f-strings for string interpolation in modern Python.

Interactive Walkthrough Examples

String Slicing & Palindrome Verification (Basic)

Using negative stride slicing to check for palindromic words.

def is_palindrome(word: str) -> bool:
    clean = word.lower().replace(" ", "")
    return clean == clean[::-1]

test_words = ["Racecar", "Python", "A Santa at NASA"]
for w in test_words:
    print(f"'{w}' is palindrome: {is_palindrome(w)}")

Explanation: clean[::-1] creates an inverted string in O(N) time.

Common Misconceptions & Exam Traps

Common Pitfall: Attempting In-Place String Mutation (TypeError)

Strings in Python are strictly immutable. Once created in memory, characters cannot be altered in place.

Buggy Code
s = "Hello"
s[0] = "J"  # TypeError: 'str' object does not support item assignment!
Correct Solution
s = "Hello"
s = "J" + s[1:]  # Construct a new string

Exam Trap Note: Exams test immutability by asking what happens when attempting `s[i] = "x"`. It raises TypeError.

Conceptual Knowledge Self-Check Quiz

Q1: Given `s = "abcdef"`, what does `s[1:5:2]` return?

  1. "bd"
  2. "ace"
  3. "bcde"
  4. "bdf"

Indices from 1 up to (not including) 5 with step 2 are index 1 ('b') and index 3 ('d'). Result is "bd".

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Use "".join(list_of_strings) instead of accumulating with += in a loop for O(N) concatenation.
  • ✅ Use str.strip(), str.split(), and str.replace() for clean text normalization.

All 26 Curriculum Modules