logo
07

String Basics

⏱️ 30 min

Python Strings Basics: Your First Step in Text Processing

What You Might Be Wondering

"A string is just a sentence. Why does it get its own lesson?"

Because in real projects, user input, logs, API responses, prompts — they're all strings. Your ability to handle text determines whether you can build anything useful.

One-Line Definition

A string is an ordered sequence of characters. You can access characters by position, slice them, and clean them up.

Real-Life Analogy

A string is like a row of seats. Each character has a seat number (index), and you can grab any value by its number.

Minimal Working Example

text = "Python"
print(text[0])    # P
print(text[-1])   # n
print(text[0:3])  # Pyt

Common Operations

s = "  hello, python  "
print(s.strip())
print(s.upper())
print(s.replace("python", "AI"))

f-string Dynamic Formatting

name = "Alice"
score = 95
print(f"{name}'s score is {score}")

Input Cleaning Example (You'll Use This Constantly)

raw_email = "  USER@EXAMPLE.COM "
clean_email = raw_email.strip().lower()
print(clean_email)  # user@example.com

Quick Quiz (3 min)

  1. Print a sentence's length plus its first and last characters.
  2. Convert an English sentence to uppercase and replace one word.
  3. Clean an email (strip whitespace + lowercase).

Quiz Rubric & Grading Criteria

  • Direction: write runnable code that covers the core requirements and edge cases from the prompt.
  • Criterion 1 (Correctness): main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.

Take-Home Task

Build a "nickname normalizer" function:

  • Strip leading/trailing whitespace
  • Collapse multiple spaces into one
  • Convert to title case

Acceptance Criteria

You can independently:

  • Read strings using indexing and slicing
  • Use strip/lower/upper/replace
  • Perform basic input cleaning

Common Errors & Debugging Steps (Beginner Edition)

  • Error message looks like gibberish: read the last line for the error type (TypeError, NameError, etc.), then trace back to the offending line.
  • Not sure what a variable holds: drop a temporary print(variable, type(variable)) to check.
  • Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.

Common Misconceptions

  • Misconception: you can modify a string in place by index.

  • Reality: strings are immutable. Any "modification" creates a new string.

  • Misconception: the right side of a slice is included.

  • Reality: slicing is left-inclusive, right-exclusive.