PythonPython StringsPython string slicing

What is string slicing?

Question 63 of 88 · Updated

On this page

String slicing selects a subsequence of a string using s[start:stop:step]. Unlike indexing, which returns one code point, slicing can select zero, one or many code points. The result is another string; the original remains unchanged.

Python's slicing rules are especially useful for extracting prefixes and suffixes, working with fixed-width fields, selecting every nth element and reversing a sequence. The important details are the exclusive stop boundary, direction-dependent defaults and handling of negative bounds.

1. Basic syntax: start inclusive, stop exclusive#

PYTHON
s = 'Python' print(s[1:4], s[:3], s[3:]) print(s[:], s[3:3] == '')

Output:

yth Pyt hon
Python True

In s[1:4], the selected positions are 1, 2 and 3. Position 4 is excluded.

Position012345
Code pointPython
Selected by s[1:4]NoYesYesYesNoNo
Loading diagram…

A slice with an omitted start begins at the appropriate boundary for its direction. With the default positive step, s[:3] begins at zero, and s[3:] continues to the end. A full slice s[:] represents the same complete value. A slice with equal start and stop selects no elements.

Because strings are immutable, slicing does not remove or modify elements of the original string. An implementation may reuse an existing string object when the result permits it; a full slice is not a promise of a separate object.

2. Negative bounds and out-of-range positions#

PYTHON
s = 'Python' print(s[-4:-1], s[-100:100]) print(repr(s[100:]), repr(s[4:1]))

Output:

tho Python
'' ''

The bound -4 refers to position 2 in this six-code-point string. The bound -1 refers to position 5, which is excluded, so the result is 'tho'.

Unlike single-element indexing, ordinary slice bounds outside the sequence are adjusted to the available range. Thus s[-100:100] selects the entire string. A start beyond the end can result in an empty slice.

A positive step cannot move from position 4 toward position 1, so s[4:1] is empty. Python does not automatically change the direction just because the start is greater than the stop.

These rules apply to valid integer or integer-like slice components. Invalid types and a zero step still raise exceptions.

3. Step size and direction#

The third component of a slice is its step. A positive step moves toward increasing indexes; a negative step moves toward decreasing indexes. The default step is 1.

PYTHON
s = 'abcdef' print(s[::2], s[1::2], s[4:0:-2]) print(s[::-1], repr(s[:-1:-1]))

Output:

ace bdf ec
fedcba ''
ExpressionSelected indexesResult
s[::2]0, 2, 4ace
s[1::2]1, 3, 5bdf
s[4:0:-2]4, 2ec
s[::-1]5, 4, 3, 2, 1, 0fedcba
s[:-1:-1]NoneEmpty string

The stop remains exclusive for either direction. For s[4:0:-2], index 0 is not included even though the progression would otherwise reach it.

To reverse an entire string, use s[::-1]. With a negative step and no explicit start, traversal begins at the last element. With a negative step and no explicit stop, traversal can continue through index zero.

A subtle distinction is that the omitted negative-direction stop is not the same as explicitly specifying -1. In s[:-1:-1], the explicit -1 refers to the last position, which is also the default start; therefore the slice is empty.

4. Direction-dependent defaults and normalized indexes#

For a string of length n, these are the conceptual defaults before selection:

Step directionDefault startDefault stopTraversal condition
Positive0nCurrent index is below the stop
Negativen - 1Boundary before index 0Current index is above the stop

The negative-direction boundary before index zero is a conceptual sentinel. It must not be confused with the literal bound -1 supplied in source syntax.

Python's built-in slice object exposes these rules through its indices method. This is useful for understanding complex slices and implementing algorithms that need the same normalized positions.

PYTHON
s = 'abcdef' part = slice(-2, None, -2) print(part.indices(len(s))) print(s[part]) print(''.join(s[i] for i in range(*part.indices(len(s)))))

Output:

(4, -1, -2)
eca
eca

The slice(-2, None, -2) object represents the same selection as s[-2::-2]. Its indices method returns normalized values for use in range. The normalized stop -1 is the exclusive boundary for that range, so indexes 4, 2 and 0 are selected.

Loading diagram…

The diagram assumes integer-like or omitted components and a valid string length. Unsupported component types fail separately.

The conceptual reconstruction using range(*part.indices(len(s))) is useful for reasoning and testing. It is not a recommendation to manually rebuild a string for ordinary slicing. Native slicing is clearer and can be more efficient.

Do not take the normalized tuple returned by indices and blindly feed it back into a new slice: the normalized negative-direction stop -1 would be interpreted again as a relative index. The normalized tuple is intended for a progression such as range.

5. Practical example: split text into fixed-width chunks#

PYTHON
def chunks(text, width): if width <= 0: raise ValueError('width must be positive') for start in range(0, len(text), width): yield text[start:start + width] print(list(chunks('ABCDEFG', 3))) print(list(chunks('', 3)))

Output:

['ABC', 'DEF', 'G']
[]

The range supplies starting positions 0, 3 and 6. Each slice selects up to three code points. The final stop extends beyond the string, so the last chunk contains only G.

This generator assumes text is a string and width is a positive integer. Its validation is executed when iteration begins, because calling a generator function does not immediately execute its body. A public interface may additionally need explicit type checks.

For n code points and fixed positive width, the chunks collectively contain n code points. Producing all of them requires O(n) traversal and copying work under the usual CPython model. The generator avoids retaining all chunks inside the function, although the example's list conversion collects them for display.

This is code-point chunking, not byte chunking. If a file format or transport imposes a byte limit, use a representation-aware boundary policy. Splitting UTF-8 bytes arbitrarily can separate parts of a multibyte encoding.

6. Practical example: mask all but a suffix#

PYTHON
def mask(text): if len(text) <= 4: return '*' * len(text) return '*' * (len(text) - 4) + text[-4:] print(mask('ABC12345'), mask('abc'), repr(mask('')))

Output:

****2345 *** ''

A negative start selects a suffix without needing to calculate its nonnegative position explicitly. The function masks all values of length four or less, so short inputs are not revealed completely.

This is a demonstration of a particular display policy for text identifiers. It preserves the code-point length and reveals the final four code points only for longer values. It is not encryption or a guarantee of anonymization. Even masked identifiers can reveal information through their suffix and length, and the original value remains present in memory. Follow the actual data-handling requirements of the application.

7. Reversing Unicode text: what the slice really does#

PYTHON
s = 'e\u0301🙂' print([hex(ord(c)) for c in s]) print([hex(ord(c)) for c in s[::-1]]) print(len(s[:2]))

Output:

['0x65', '0x301', '0x1f642']
['0x1f642', '0x301', '0x65']
2

The original string contains e, a combining acute accent and an emoji code point. Its reversed sequence contains the emoji, the accent and then e.

Slicing operates on Unicode code points, not grapheme clusters. Reversal by s[::-1] may separate an accent from the letter with which it was displayed, or disrupt a multi-code-point emoji sequence.

For ordinary ASCII words, code-point reversal generally matches the intended visual reversal. For user-facing Unicode text, define whether reversal means code points, grapheme clusters, or another logical unit. Grapheme-aware segmentation may be required before reversal. Bidirectional text also has display-order considerations that a simple slice cannot address.

The expression s[::-1] produces the reversed code-point sequence without modifying s. Under the ordinary CPython cost model, producing a reversed string of length n requires O(n) time and O(n) result storage, except for possible trivial cases or implementation optimizations.

An alternative is ''.join(reversed(s)), which also reverses by code point, not by grapheme cluster. The slice is generally the clearest expression for this specific operation.

8. Slice objects and integer-like components#

PYTHON
class Two: def __index__(self): return 2 print('abcdef'[Two(): :Two()]) print('abcdef'[2:3], 'abcdef'[2])

Output:

ce
c c

The __index__ method provides an exact integer interpretation for objects used in integer-index operations. In this example, both start and step are interpreted as 2. Omitted components are represented by None.

The second output demonstrates that a one-element slice and a valid single-element index can return equal strings. Their boundary behavior is different: indexing a missing position raises IndexError, whereas a corresponding out-of-range slice can return an empty string.

Slice objects expose start, stop and step attributes and are useful when a selection needs to be stored or reused across sequences. Normalization depends on the length of the particular sequence, so one slice object can select different actual positions when applied to strings of different lengths.

9. Common errors and edge cases#

OperationResult
'abc'[::0]ValueError: zero step
'abc'[1.5:]TypeError: unsupported bound
'abc'[:'2']TypeError: unsupported bound
'abc'[::1.5]TypeError: unsupported step
''[::-1]Empty string
'abc'[10:20]Empty string
'abc'[-1:]c

The four invalid native slicing cases and the nonpositive chunk-width validation were confirmed independently. A slice object can itself be constructed with a zero step, but applying it to an ordinary string or normalizing it with indices raises ValueError.

Do not assume clipping slice bounds makes arbitrary external inputs valid. If an application requires an exact field of a specified length, check that the field actually exists. A silently shortened slice may otherwise conceal an incomplete record.

10. Complexity and memory#

Let k denote the number of selected code points. For ordinary CPython str values and bounded-size index inputs, a proper slice that copies k code points generally requires O(k) time and O(k) resulting storage. A full slice or another special case may reuse an existing immutable object. The language does not require a specific storage representation or allocation strategy.

OperationTypical CPython cost
Read a single valid indexO(1)
Select a proper slice of k code pointsO(k)
Reverse n code pointsO(n)
Store m materialized slices of length k eachO(m*k) result storage, subject to reuse

The amount copied depends on the selected elements, not merely on the distance between the original bounds. A slice selecting every tenth code point can produce substantially fewer elements than the full interval.

Unlike a range slice, which can often represent a sub-progression without materializing every element, an ordinary nontrivial string slice typically constructs text storage for its result in CPython. Avoid assuming that string slices are guaranteed zero-copy views.

The validation suite checked 2,000 seeded random slices against a conceptual reconstruction using slice.indices and range, including omitted bounds, negative bounds, both step directions, empty strings and mixed Unicode code points.

Frequently asked questions#

Is the stop index included in a Python slice?#

No. It is an exclusive boundary for both positive and negative steps.

What happens when a slice goes past the end?#

Valid integer bounds are adjusted to the available sequence. A slice may return a shortened result or an empty string instead of raising IndexError.

How can I reverse a string with slicing?#

Use s[::-1]. It visits the string's code points from last to first. It does not guarantee preservation of multi-code-point grapheme clusters.

Why is s[:-1:-1] empty?#

The negative step defaults its start to the last position, while the explicit stop -1 also refers to that last position. The stop is exclusive, so nothing is selected.

Does slicing change the original string?#

No. Strings are immutable. Slicing returns a string result without changing the original value.

Can the slice step be zero?#

No. A zero step raises ValueError when applied to a string.

Interview-ready answer#

Python string slicing selects a subsequence using s[start:stop:step]. The start is inclusive, the stop is exclusive, and the step defaults to one. Negative bounds refer to positions relative to the end; a negative step traverses backward. Omitted start and stop depend on the direction, which makes s[::-1] a concise way to reverse code points. Valid integer slice bounds are adjusted to the sequence length, unlike indexing, which raises IndexError for missing positions. Slicing returns an immutable str result and does not modify its source. A typical proper CPython slice takes time and storage proportional to the number of selected code points. For Unicode text, remember that slicing operates on code points rather than displayed grapheme clusters.

Official references#

Verification note: Eight fenced Python examples were executed in separate namespaces on CPython 3.13.5 and matched their documented outputs. Five expected-exception tests passed, along with 2,000 seeded randomized assertions comparing native slicing to reconstruction from normalized indices. The two Mermaid diagrams were manually reviewed; the local Mermaid package and CLI were unavailable, so parser-level validation and public-site rendering were not performed. Grapheme-aware reversal was discussed conceptually, not tested using a third-party library. Official references are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design