PYTHON / CHAPTER 02

Working with strings

Beginner

Read, slice, and clean text with explicit rules for spaces and separators.

By the end of this chapter

  • Read string indexes and slices
  • Distinguish literal separators from whitespace splitting
  • Choose edge trimming or exact prefix removal

The idea

A string stores text between matching quotes. Its positions start at zero: "cat"[0] is "c". A slice such as "planet"[1:4] returns positions 1, 2, and 3; the stop position is excluded. Negative indexes count from the end, and an omitted bound uses that edge. A third slice value sets a step: [1:5:2] selects positions 1 and 3. For these first examples, use ordinary ASCII letters and spaces.

Strings are immutable: a method returns a result without changing the original. split() without an argument separates runs of whitespace and omits empty edge fields. split(",") uses the literal comma separator and keeps empty positions. In the worked example, "a,,b" contains an empty middle field, so splitting on commas must preserve it.

strip() removes surrounding whitespace, not interior spaces. strip("ab") has a different rule: it removes any a or b characters from either edge. To remove exactly one known prefix when it is present, use removeprefix("ID:"). Start with a written rule, then test normal input, empty input, and repeated separators. Text beyond ASCII can contain multiple code points in one displayed character, so character-counting tasks need a more precise contract later.

Python example
s = "  red   blue  "
print(s.split())
print("a,,b".split(","))
print(s == s.strip())
Result
['red', 'blue']
['a', '', 'b']
False

Whitespace splitting and literal-delimiter splitting intentionally treat empty fields differently.

Try it yourself

Parse comma-separated labels while preserving empty positions and trimming each field.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open Python coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which value preserves the missing middle field?