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.

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

next positionnext positionnext positionnext position0h1e2l3l4o
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.

Locating a Character

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

Start at index 0: The first character h is assigned index 0.

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.

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

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.

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?

Include the start: Index 1 identifies e, so e is included.

Continue before the end: Indices 2 and 3 identify l and l, so both are included.

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

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

slice 1 to 4helloindices 0 through 4ellindices 1 through 3oindex 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.

direct character updateconcatenation or methodhellooriginal stringcharacter changecannot change in placenew stringcreated from stringoperations
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.

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.

not foundnot foundfoundhcheck targetecheck targetltarget foundstopsearch ends
How does a program move through characters one at a time and stop when the target is found?

Distinguishing Traversal from Search

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

Begin with the first character: The program examines h.

Continue in order: The program examines e because h is not the target.

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

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.

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

Common Mistakes

  • Treating the first character as index 1.

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

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

  • Including the end index in a slice.

    The end index of a slice is exclusive.

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

  • Trying to change one character in place.

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

    Fix: Create a new string through concatenation or a method.

  • Confusing traversal with search.

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

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

  • Treating the empty string as an invalid or undefined value.

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

    Fix: 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.

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

Key Takeaways

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