Concepts / String Indexing and Accessing Characters

String Indexing and Accessing Characters

The find() method locates the position of a substring and returns its starting index; use find(substring, start_pos) to search from a specific position onward.

  • 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…

A Position Is a Landmark

A string can contain several pieces of information mixed together, such as an email address, a timestamp, or other text. Parsing means breaking that larger string into smaller pieces so that you can isolate the exact data you need. The find() method helps by locating a substring and reporting the position where that substring starts.

Key point

Treat the positions returned by find() as landmarks. Once you know where important characters or substrings occur, you can use those positions as boundaries for a slice.

Mapping Characters to Indices

The position returned by find() is the starting index of the substring it found. In a generated example such as the text containing an email address followed by a status word, find("@") might identify the @ character at index 13. That number is not the position of the whole email address; it is specifically the position where the @ substring begins. The distinction matters because a later slice may need to begin one position after that landmark.

@landmarksslice startsite.orgindices 14 through 21spaceslice endmove one positionstarts atends before
Which character position does find() return, and how does that position map onto the characters in the string?
Definition

The find() method locates the position of a substring and returns its starting index. If the search begins from a specified position, find(substring, start_pos) searches from that position onward.

From Landmarks to Slices

Worked example

Extracting a Domain Between Two Landmarks

A larger string contains an email address and other information. Use the position of the @ character and the position of the next space to isolate the domain.

  1. 1
    Locate the first landmark

    find('@') returns 21. This means that the @ symbol begins at index 21.

  2. 2
    Search from that landmark

    find(' ', atpos) searches for a space beginning at position 21 and returns 31. The first space after the @ is therefore at index 31.

  3. 3
    Move past the @ symbol

    The domain begins at atpos + 1, which is position 22. Starting at atpos itself would include the @ symbol in the extracted text.

  4. 4
    Use the second landmark as the boundary

    The slice data[atpos+1:sppos] starts at position 22 and stops before position 31. Because the end of a slice is excluded, the space at index 31 is not included.

Result

The extracted domain is uct.ac.za.

find('@')atpos21@ positionfind(' ', atpos)sppos31space position22:31atpos + 1 : spposuct.ac.zaextracted textreturnsstarting positionreturnsadd 1end boundaryextracts
How does the index returned by find() flow into the start and end positions used by a slice?

A slice written with a start and end boundary extracts characters from the start position up to, but not including, the end position. This is why the @ landmark is changed to atpos + 1 and the space position can be used directly as the end boundary. The two find() results become the inputs that define the exact portion to extract.

Searching from a Later Position

The two-argument form find(substring, start_pos) changes where the search begins. Instead of looking from the beginning of the string, it searches for the substring from start_pos onward. In the source example, the search for a space begins at the position of the @ symbol, so the result identifies the first space after that landmark rather than an earlier space elsewhere in the string.

find(' ')search from beginningfind(' ', 21)search from index 21earlier spacefirst match31first space from index 21onwardreturnsreturns
What changes when find(substring, start_pos) begins searching from a later position instead of the beginning?

Tracing a Parsing Failure

When parsing produces an unexpected result, follow the indices in order. First inspect the values returned by find(). Next check whether the slice starts at the intended character. Finally check whether the end boundary is the position of the delimiter that should be excluded. Printing intermediate values makes it possible to see which landmark or boundary became incorrect.

  • Common mistake

    Using the position of the @ symbol as the slice start

    What it looks like

    Starting at atpos instead of atpos + 1

    Why it fails

    The @ symbol becomes part of the extracted text.

    Do this instead

    Add one to the @ position when the desired data begins immediately after @.

  • Common mistake

    Using the wrong space position

    What it looks like

    Searching for a space from the beginning when an earlier space exists

    Why it fails

    The slice may end before the intended domain or data segment.

    Do this instead

    Pass the relevant landmark as the start_pos argument so find() searches from that point onward.

  • Common mistake

    Ignoring a failed search

    What it looks like

    Using a find() result without checking whether it is -1

    Why it fails

    A missing landmark does not provide a valid position for the intended slice.

    Do this instead

    Verify that find() returned a valid index before using the result in slicing.

  • Common mistake

    Inspecting only the final extracted text

    What it looks like

    Trying to fix a wrong result without printing atpos or sppos

    Why it fails

    The error may be in a landmark search rather than in the slice itself.

    Do this instead

    Print intermediate find() results and then inspect the slice boundaries step by step.

Best practice

For parsing logic, name and inspect each landmark separately before combining them into a slice. This keeps the flow visible: locate the first marker, locate the next marker from the correct starting position, calculate any needed offset, and then extract the range.

Practice the Index Flow

MEDIUM

A string contains a marker at one position and a second delimiter later in the string. Describe the four values you would trace to extract the text between them: the first find() result, the second find() result using the first as start_pos, the adjusted slice start if the first marker should be skipped, and the slice end.

Hints
  • Treat each find() result as a landmark.
  • Decide whether the first landmark itself belongs in the extracted text.
  • Remember that the slice end is excluded.
  1. 1
    Use find() to locate the starting index of a substring. Use find(substring, start_pos) when the search must begin at a later landmark. Use slicing to extract characters from a start index up to, but not including, an end index. When debugging, verify every find() result, check for -1, and trace how each index becomes a slice boundary.

Key Takeaways

  • find() returns the starting index of the substring it locates.
  • The optional start_pos argument makes find() search from a later position onward.
  • A slice uses a start boundary and an exclusive end boundary to extract text.
  • Parsing combines landmark searches with slicing to isolate data from a larger string.
  • Check for -1 and inspect intermediate indices when debugging parsing logic.

Related concepts

More concepts starting with S