Concepts / String Basics and Indexing

String Basics and Indexing

When you see a string method such as startswith(), find(), or join(), you are using behavior provided by the str class.

  • Programming
Interactive lab

Try it: Indexing and Slicing

How Python indexes a sequence from 0 (or from the end with negative numbers) and how a slice start:stop:step picks positions — with the exact CPython rules for omitted and out-of-range bounds.

How it works

  1. Positions run 0 … len−1; negative positions count back from the end (−1 is the last).
  2. An index outside the string raises IndexError.
  3. A slice resolves start and stop (omitted → the ends; out of range → clamped), then walks by step, stopping before stop.
  4. A negative step walks backwards; a step of 0 is a ValueError.

Default run (7 steps): 'PYTHONIC'[1:6:2]: a slice copies characters from start up to (not including) stop, moving by step. … 'PYTHONIC'[1:6:2] → 'YHN' (positions 1, 3, 5).

Simplified: Works on a short string (up to 16 printable ASCII characters); lists slice by exactly the same rules.

Educational simulation

Loading the simulation…

Interactive lab

Try it: String methods, character by character

How Python's str methods (split, strip, replace, find, count, startswith, join, in …) scan a string character by character — and that each call returns a new value while the original string never changes.

How it works

  1. Each method call reads the string it is called on from left to right (strip also trims from the right end).
  2. split() with no separator skips runs of whitespace and never returns empty strings; split(sep) cuts at every occurrence of sep and can return empty pieces; maxsplit limits the number of cuts.
  3. find, index, count, replace and `in` slide a window along the string; occurrences never overlap, find gives -1 and index raises ValueError when nothing matches.
  4. strip(chars) removes any of the given characters (a set, not a substring) from the ends until it meets one that is not in the set.
  5. Strings are immutable: every call returns a new str, list, int or bool, and the next call in the chain works on that new value.

Default run (62 steps): s = ' Apples, pears,,figs '. Evaluate ' | '.join(s.strip().lower().split(',')) one method call at a time, left to right. … ' | '.join(s.strip().lower().split(',')) → 'apples | pears | | figs'. And s is still ' Apples, pears,,figs '.

Simplified: Printable ASCII text up to 30 characters and up to four chained calls with short arguments. CPython searches with a faster algorithm (fastsearch) than the window-by-window scan shown, but the results are the same.

Educational simulation

Loading the simulation…

A String Is More Than Text

A string is a sequence of text, but in Python it is also an object belonging to the str class. Because it is an object, a string has methods: operations that can check, search, or transform text. This means that working with a string involves both the characters it contains and the operations available through str.

Key point

When you see a string method such as startswith(), find(), or join(), you are using behavior provided by the str class.

str classstring behaviora string objecttext valuestring methodschecking, searching,transformingdefinesprovidesuses
How is a particular string object connected to the str class, and where do its methods come from?

Character Positions

Indexing lets you refer to characters by position. Positive indices count from the beginning of the string, starting at zero. Negative indices count from the end, with the final character at position negative one. Indexing is useful when a task concerns a particular character rather than the entire string.

0P-6P1y-5y2t-4t3h-3h4o-2o5n-1n
Which character does each index refer to when positions are counted from the beginning or from the end?
Worked example

Finding a Character by Position

Use the string Python to identify its first character and its final character.

  1. 1
    First character

    The first character is reached with positive index 0.

  2. 2
    Final character

    The final character is reached with negative index -1.

  3. 3
    Check both directions

    Positive indexing starts at the beginning, while negative indexing starts at the end.

Result

For Python, index 0 identifies P and index -1 identifies n.

Three Useful String Methods

String methods let you express common text-manipulation tasks directly. startswith() checks whether a string begins with specified characters. find() locates a substring within a string. join() combines a sequence of strings using a delimiter. These methods illustrate three different kinds of work: checking, searching, and combining.

textPythonstartswith()prefix checkjoined stringdelimiter between valuesfind()substring locationcheck resulttrue or falsestring sequenceseveral valuessearch resultsubstring positioninspectsearchcombinereturnsreturnsjoin with delimiter
How does text move through startswith(), find(), and join(), and what kind of result does each method produce?
Worked example

Choosing the Right Method

Select a string method for each task: check whether a title begins with a prefix, locate a word inside a sentence, or combine several words with a separator.

  1. 1
    Check a beginning

    Use startswith() when the question is whether text begins with particular characters.

  2. 2
    Locate text

    Use find() when the task is to locate a substring.

  3. 3
    Combine values

    Use join() when a sequence of strings must be combined with a delimiter.

Result

The method should match the operation: startswith() checks, find() searches, and join() combines.

Why the Original Stays the Same

String methods return new values rather than modifying the original string. This behavior follows from string immutability: once a string exists, a method does not change that original string's contents. When a method appears to transform text, think of the result as a new value that can be used separately.

original stringunchanged textoriginal stringsame textstring methodrequested operationnew valuemethod resultremainsreturns
What happens to the original string when a string method appears to change its contents?

Discovering More with help(str)

The three methods in this lesson are only part of the behavior available for str objects. Python's built-in help() function can display the documentation for the str class. Running help(str) reveals the available methods and explains what each method does, which arguments it accepts, and what it returns.

  1. 1
    Identify the text task you need to solve.
  2. 2
    Use help(str) to inspect the methods available for string objects.
  3. 3
    Read the method descriptions, including accepted arguments and returned values.
  4. 4
    Choose a method whose documented behavior matches the task.
  5. 5
    Use the returned value while remembering that the original string remains unchanged.
Key point

Documentation is part of the programming process. You do not need to memorize every string method when help(str) can show the complete range and explain how each method behaves.

Mistakes with String Operations

  • Common mistake

    Treating startswith() as a general substring search

    What it looks like

    Using startswith() when the needed text may appear anywhere in the string

    Why it fails

    startswith() tests the beginning of a string; it is not the method described for locating a substring.

    Do this instead

    Use startswith() for a prefix check and find() when the task is to locate a substring.

  • Common mistake

    Assuming find() combines several strings

    What it looks like

    Choosing find() when the task is to assemble words with a delimiter

    Why it fails

    find() locates a substring, while join() combines a sequence of strings.

    Do this instead

    Choose join() for combining strings with a delimiter.

  • Common mistake

    Expecting a string method to modify the original string

    What it looks like

    Assuming that the original text has changed after a method call

    Why it fails

    String methods return new values because strings are immutable.

    Do this instead

    Work with the returned value and treat the original string as unchanged.

  • Common mistake

    Guessing a method instead of checking its documentation

    What it looks like

    Trying to remember an unfamiliar string operation without consulting help(str)

    Why it fails

    The str class contains many methods, and their documentation explains their behavior, arguments, and return values.

    Do this instead

    Use help(str) to discover suitable methods and verify how they work.

Try the Method Match

EASY

For each task, choose between startswith(), find(), and join(): determine whether a product code begins with a given prefix; locate a particular word in a sentence; combine a list of words with a chosen delimiter.

Hints
  • Ask whether the task checks a beginning, searches for a location, or combines values.
  • Remember that join() uses a delimiter to combine a sequence of strings.
  • If you cannot remember another string method, consult help(str).

What do you think happens?

A string method appears to produce transformed text. Does that operation modify the original string or return a new value?

  • It modifies the original string

  • It returns a new value and leaves the original unchanged

Reveal answer
Answer:

It returns a new value and leaves the original unchanged.

Strings are immutable, so string methods do not modify the original string.

Key Takeaways

  • Strings are objects belonging to the str class and provide methods for checking, searching, and transforming text.
  • Positive string indices count from the beginning, while negative indices count from the end.
  • startswith() checks a prefix, find() locates a substring, and join() combines strings with a delimiter.
  • String methods return new values because strings are immutable; they do not modify the original string.
  • Use help(str) to discover available string methods and read their arguments, behavior, and return values.

Related concepts

More concepts starting with S