Concepts / String Slicing Techniques

String Slicing Techniques

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…

A String as Positions and Values

A string is more than a line of characters. It is a sequence: an ordered set of values identified by integer indices beginning at 0. In the string 'hello', the characters appear in order, and each character has a position that can be used to select or examine it.

0h1e2l3l4onextnextnextnext
How do integer indices map to the characters in an ordered string sequence?
Definition

An index selects one item from a sequence. A slice selects a range of items. A sequence provides the ordered structure; indices identify positions within it; slices select portions of that structure.

Tracing a Slice Boundary

A slice is determined by a start index and an end index. The start is included, while the end is excluded. This is called a half-open interval. For example, selecting from index 1 to index 4 in 'hello' includes the characters at indices 1, 2, and 3: 'e', 'l', and 'l'. The character at index 4, 'o', is not included.

0h1e2l3l4orange ends before
Which characters does a slice select when its start and end positions are applied to a string?
Worked example

Selecting the Middle of a String

Use the start index 1 and the end index 4 to select part of the string 'hello'.

  1. 1
    Locate the start

    Index 1 identifies the character 'e'. Because the start is inclusive, this character belongs to the slice.

  2. 2
    Move through the range

    The next selected positions are indices 2 and 3, containing 'l' and 'l'.

  3. 3
    Stop before the end

    Index 4 contains 'o', but the end index is exclusive, so that character is not selected.

Result

The selected characters are 'ell'.

Traversal Through Characters

Traversal means visiting every item in a sequence systematically. For a string, traversal moves through its characters in order. It is useful when a task requires examining every character, counting occurrences, or applying a transformation to all items.

0h1e2l3l4oadvanceadvanceadvanceadvance
How does control move from one character index to the next while traversing a string?

Traversal and slicing answer different questions. A slice selects a specified range and produces that portion of the sequence. Traversal describes the systematic process of visiting items. A program can traverse a string to count a character, inspect each character, or transform every item.

Worked example

Counting During Traversal

Examine every character in a string and count how many times a chosen character appears.

  1. 1
    Begin with a counter

    Use a counter to remember how many matching characters have been encountered.

  2. 2
    Visit each character

    Move through the string in order and compare each character with the chosen target.

  3. 3
    Update on a match

    Increase the counter whenever the current character matches the target.

Result

The counter records the number of occurrences found during the traversal.

Search as Early-Stopping Traversal

Search is a specialized form of traversal. The process examines characters or positions one at a time and checks whether the target has been found. Unlike a traversal that must visit every item, a search stops as soon as it finds the target. A flag can remember whether the target was found.

StartCurrent characterinspectTargetfound?FoundNext positioncontinueNot foundbegincompareyesnoadvancesequence ends
How does a search inspect positions and determine whether a target has been found?
Key point

The defining difference is the stopping rule: traversal visits every item, while search can stop at the first successful match. A flag is useful when later logic needs to remember whether the search succeeded.

Immutable String Results

Strings are immutable. This means an individual character cannot be changed in place within the original string. Immutability does not prevent string operations; it means that an operation that appears to modify text must create a new string instead. Concatenation and string methods can produce new strings while leaving the original unchanged.

Original stringunchanged valueOriginal stringunchanged valueString operationconcatenation or methodNew stringnew resultinputresult created
What changes when a string operation creates a new string instead of modifying the original?
Edge case

The empty string is a valid string with length 0 and no items. It is not an error or an undefined state. A string operation can legitimately produce an empty string, including a search or selection that finds no characters.

Calling String Methods

String objects provide methods for operations such as converting text to uppercase, finding a character position, 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. The dot connects the specific string object to the operation being requested.

stringobject.connectsmethodoperation()invokeaccessselectcall
How does a string object connect to the method being called when dot notation is used?
Best practice

When reading a string operation, identify three parts in order: the string object receiving the operation, the method name, and the parentheses that invoke it. This makes it clear which string the method acts on.

Mistakes Beginners Make

  • Common mistake

    Including the end index in a slice

    What it looks like

    Treating the range from index 1 to index 4 in 'hello' as including index 4

    Why it fails

    The start index is inclusive, but the end index is exclusive.

    Do this instead

    Select indices 1, 2, and 3; index 4 is the stopping boundary.

  • Common mistake

    Confusing an index with a slice

    What it looks like

    Expecting one index to return a range of characters

    Why it fails

    An index selects one item, while a slice selects a contiguous range.

    Do this instead

    Use an index when one character is needed and a start-end range when several characters are needed.

  • Common mistake

    Expecting a string character to change in place

    What it looks like

    Trying to replace one character inside the original string directly

    Why it fails

    Strings are immutable, so individual characters cannot be changed in place.

    Do this instead

    Create a new string through concatenation or a string method.

  • Common mistake

    Confusing traversal with search

    What it looks like

    Continuing through the entire string after the target has already been found

    Why it fails

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

    Do this instead

    Stop at the first match when the task is to find whether or where a target appears.

  • Common mistake

    Treating an empty string as an invalid result

    What it looks like

    Assuming a selection or search that produces no characters must indicate an error

    Why it fails

    The empty string is a valid string with length 0.

    Do this instead

    Handle the empty string as a legitimate value.

Practice the Distinctions

MEDIUM

For the string 'hello', explain which characters are selected by a slice with start index 1 and end index 4. Then describe how a traversal differs from a search for the character 'l'. Finally, explain why replacing one character requires creating a new string rather than changing the original in place.

Hints
  • Remember that the start is included and the end is excluded.
  • A traversal visits every item; a search can stop when its target is found.
  • Immutability means the original string cannot have an individual character changed in place.

What do you think happens?

A slice of 'hello' starts at index 1 and ends at index 4. Which characters are selected?

  • e, l, l

  • h, e, l, l

  • e, l, l, o

  • l, l, o

Reveal answer
Answer:

e, l, l

Index 1 is included, indices 2 and 3 are included, and index 4 is excluded.

Key Takeaways

  1. 1
    Strings are ordered sequences of characters whose integer indices begin at 0.
  2. 2
    An index selects one item, while a slice selects a range with an inclusive start and an exclusive end.
  3. 3
    Strings are immutable, so operations create new strings rather than changing individual characters in place.
  4. 4
    Traversal visits sequence items systematically; search is traversal that can stop when a target is found.
  5. 5
    String methods are invoked through dot notation, and counters or flags help manage traversal and search tasks.

At a glance

  • A string is an ordered sequence, and each character has an integer index beginning at 0.
  • A slice includes its start index but excludes its end index.
  • String immutability means that operations create new strings instead of changing individual characters in place.
  • Traversal examines items systematically, while search may stop at the first matching target.
  • Dot notation invokes a method on a particular string object.

Related concepts

More concepts starting with S