Concepts / String Indexing and Access

String Indexing and Access

A sequence is an ordered set of values identified by integer indices starting at 0; strings are sequences of characters.

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

One String, Many Positions

A string is more than a visual row of characters. It is a sequence: an ordered set of values identified by integer indices. For example, the five characters in the string hello each occupy a position, so a program can select one character or a range of characters instead of treating the string as an indivisible value.

Key point

An index selects one item from a sequence. A slice selects a contiguous range of items.

0h1e2l3l4onext positionnext positionnext positionnext position
Which character does each integer index refer to in the string hello, and how does indexing begin at 0?

Reading Positions Precisely

The integer assigned to a character is its index. Indexing begins at 0, not 1. Therefore, the first character has index 0, the second has index 1, and so on. In hello, the two l characters occupy different positions even though they have the same value: one is at index 2 and the other is at index 3. An index identifies a position, and using that position selects a single character.

Worked example

Locating a Character

Determine the character selected by index 3 in the string hello.

  1. 1
    Start at index 0

    The first character h is assigned index 0.

  2. 2
    Move through the sequence

    The characters are ordered as h at 0, e at 1, l at 2, l at 3, and o at 4.

  3. 3
    Select the position

    Index 3 identifies the second l, because an index selects one item at one specific position.

Result

Index 3 selects the second l in hello.

Selecting a Range

A slice selects a contiguous range rather than one character. It uses a start index and an end index. The start is inclusive, so the character at the start position is included. The end is exclusive, so the character at the end position is left out. This is called a half-open interval.

Worked example

Following a Slice Boundary

A slice starts at index 1 and ends at index 4 in the string hello. Which characters belong to the slice?

  1. 1
    Include the start

    Index 1 identifies e, so e is included.

  2. 2
    Continue before the end

    Indices 2 and 3 identify l and l, so both are included.

  3. 3
    Stop before the end index

    Index 4 identifies o, but the end index is exclusive, so o is not included.

Result

The slice contains ell: the characters at indices 1, 2, and 3.

helloindices 0 through 4ellindices 1 through 3oindex 4slice 1 to 4
Which characters are included when a slice runs from index 1 to index 4?

Why Original Strings Stay Fixed

Strings are immutable. This means an individual character cannot be changed in place inside the original string. An operation that appears to modify one character cannot update that character directly. Instead, a modified version must be created as a new string, such as by joining parts of the original with new characters or by using a string method that returns a new string. The original string remains unchanged.

hellooriginal stringcharacter changecannot change in placenew stringcreated from stringoperationsdirect character updateconcatenation or method
What happens to the original string when an operation appears to change one of its characters?

Methods and Dot Notation

Strings have methods that perform operations such as converting text to uppercase, finding the position of a character, or replacing one substring with another. To invoke a method, write the string or the variable holding the string, then a dot, then the method name followed by parentheses. This connects the operation to the specific string object on which it should run.

  • The string or string-holding variable identifies the object receiving the operation.
  • The dot connects that object to a method.
  • The method name identifies the operation.
  • Parentheses indicate that the method is being invoked.
Key point

A method can return a new string or provide another result while leaving the original string unchanged, because strings are immutable.

Traversal Before Search

Traversal means visiting every item in a sequence systematically and in order. String traversal is useful when you need to examine every character, count occurrences, or apply a transformation to all items. Search is a specialized traversal: the program checks characters one at a time and stops as soon as it finds the target. If the target appears early, search does not need to continue through the rest of the string.

hcheck targetecheck targetltarget foundstopsearch endsnot foundnot foundfound
How does a program move through characters one at a time and stop when the target is found?
Worked example

Distinguishing Traversal from Search

Suppose a program examines the string hello while looking for the character l.

  1. 1
    Begin with the first character

    The program examines h.

  2. 2
    Continue in order

    The program examines e because h is not the target.

  3. 3
    Find the target

    The program examines the l at the next position and finds the target.

  4. 4
    Stop the search

    Because this is a search, the program can stop when the target is found. A traversal intended to inspect every character would continue instead.

Result

Search may stop at the first matching character; traversal visits every character when the task requires complete examination.

Common Mistakes

  • Common mistake

    Treating the first character as index 1.

    What it looks like

    Assuming the first character of hello has index 1.

    Why it fails

    Sequence indices start at 0, so the first character has index 0.

    Do this instead

    Count positions from 0: h is at 0, e is at 1, and the remaining characters follow in order.

  • Common mistake

    Including the end index in a slice.

    What it looks like

    Expecting a slice from index 1 to index 4 in hello to include o.

    Why it fails

    The end index of a slice is exclusive.

    Do this instead

    Include the start position and every position before the end position; indices 1, 2, and 3 produce ell.

  • Common mistake

    Trying to change one character in place.

    What it looks like

    Expecting the original string to be updated by assigning a new character to one position.

    Why it fails

    Strings are immutable, so individual characters cannot be changed in the original string.

    Do this instead

    Create a new string through concatenation or a method.

  • Common mistake

    Confusing traversal with search.

    What it looks like

    Continuing to inspect every character when the task only requires finding whether an early target exists.

    Why it fails

    Search is a specialized traversal that stops when the target is found.

    Do this instead

    Stop once the target is found when complete traversal is not required.

  • Common mistake

    Treating the empty string as an invalid or undefined value.

    What it looks like

    Assuming a string with no characters cannot be a legitimate result.

    Why it fails

    The empty string is a valid string with length 0 and no items.

    Do this instead

    Handle the empty string as an ordinary possible string value.

Empty Strings and Practical Checks

The empty string is a valid string value. It has length 0 and contains no items. It can appear when a user provides no input or when a search produces an empty result. Because it is still a string, it should be handled as a legitimate value rather than automatically treated as an error or an undefined state.

Best practice

When reasoning about a string operation, identify four things: the sequence being examined, the index or range being selected, whether the operation examines one item or many, and whether the result creates a new string or only reports information about the original.

EASY

For the string hello, explain which characters belong to the slice from index 0 to index 2, then describe how a search for l differs from a traversal that counts every character.

Hints
  • The slice includes its start index and excludes its end index.
  • A search can stop when it finds the first l.
  • A complete traversal continues through every character.

Key Takeaways

  1. 1
    A string is a sequence of characters arranged in order and identified by integer indices beginning at 0.
  2. 2
    An index selects one character, while a slice selects a contiguous range with an inclusive start and an exclusive end.
  3. 3
    Strings are immutable: operations cannot replace individual characters in place, but they can create new strings.
  4. 4
    Dot notation invokes a method on a particular string object.
  5. 5
    Traversal examines sequence items systematically, while search is a traversal that can stop when a target is found.
  6. 6
    Counters and flags help record results during traversal and search, and the empty string is a valid string with length 0.

At a glance

  • Strings are ordered sequences, so every character has an integer index beginning at 0.
  • Indexing selects one item; slicing selects a range from an inclusive start to an exclusive end.
  • String immutability prevents in-place character changes but still allows new strings to be created.
  • Methods are invoked with dot notation on a specific string object.
  • Traversal visits characters systematically, while search can stop when its target is found.

Related concepts

More concepts starting with S