Key Takeaways: Strings — Text Processing and Manipulation

One-Sentence Summary

Strings are immutable sequences of characters — you process text by creating new strings from old ones using indexing, slicing, and a rich set of built-in methods.

Core Concepts

Indexing and Slicing

Operation Syntax Example Result
Index (first) s[0] "Python"[0] "P"
Index (last) s[-1] "Python"[-1] "n"
Slice s[start:stop] "Python"[0:3] "Pyt"
Slice (from start) s[:stop] "Python"[:3] "Pyt"
Slice (to end) s[start:] "Python"[3:] "hon"
Slice (with step) s[::step] "Python"[::2] "Pto"
Reverse s[::-1] "Python"[::-1] "nohtyP"

Key rule: The stop index is exclusives[0:3] gives indices 0, 1, 2.

Immutability (Threshold Concept)

What You Might Try What Actually Happens What You Should Do
s[0] = "X" TypeError s = "X" + s[1:]
s.upper() (expecting s to change) s is unchanged s = s.upper()
s.replace("a", "b") (expecting s to change) s is unchanged s = s.replace("a", "b")

The rule: String methods return new strings. They never modify the original. Always assign the result.

Essential String Methods

Method Purpose Returns Example
upper() / lower() Change case str "Hi".lower() -> "hi"
strip() Remove whitespace str " hi ".strip() -> "hi"
split(sep) Break into list list "a,b".split(",") -> ["a","b"]
sep.join(list) Combine list str ",".join(["a","b"]) -> "a,b"
replace(old, new) Substitute str "ab".replace("a","x") -> "xb"
find(sub) First position int (-1 if absent) "abc".find("b") -> 1
count(sub) Occurrences int "aab".count("a") -> 2
startswith(s) Prefix check bool "abc".startswith("ab") -> True
endswith(s) Suffix check bool "abc".endswith("bc") -> True
isdigit() All digits? bool "42".isdigit() -> True
isalpha() All letters? bool "hi".isalpha() -> True
isalnum() All alphanumeric? bool "hi2".isalnum() -> True

F-String Format Specs

Spec Meaning Example Result
:<10s Left-align, width 10 f"{'hi':<10s}" "hi "
:>10s Right-align, width 10 f"{'hi':>10s}" " hi"
:^10s Center, width 10 f"{'hi':^10s}" " hi "
:.2f 2 decimal places f"{3.14159:.2f}" "3.14"
:, Thousands separator f"{1000000:,}" "1,000,000"
:.1% Percentage f"{0.856:.1%}" "85.6%"

Escape Characters

Escape Meaning
\n Newline
\t Tab
\\ Literal backslash
\" Literal double quote
r"..." Raw string (no escaping)

Common Patterns to Remember

  1. Clean user input: user_input.strip().lower()
  2. Case-insensitive comparison: if text.lower() == "yes":
  3. Validate before converting: if raw.isdigit(): num = int(raw)
  4. Split, process, rejoin: " ".join(text.split()) (normalize whitespace)
  5. Reverse a string: text[::-1]
  6. Check for substring: if "keyword" in text.lower():

TaskFlow v0.6 Summary

  • Search: Case-insensitive keyword search using lower() and the in operator
  • Display: Formatted table output with f-string alignment specs
  • Validation: isdigit() check before int() conversion
  • Cleaning: strip() on every input() call

What's Next

Chapter 8 introduces lists and tuples — mutable and immutable sequences. The indexing and slicing you learned here work identically on lists. The key new concept: mutability — what happens when sequences can be changed in place (the opposite of string immutability).