Skip to main content

Slicing

Slice syntax gives you a section of a string instead of the whole thing.

Write the index where the section begins and the index where it stops, with a colon between them.

Note: Counting starts at 0, so index 0 is the first character.

Example

Take the characters at positions 2, 3 and 4. The end position, 5, is left out:

Prompt
Write a Python program that slices a string from position 2 to position 5 (not included) and prints the result.
Output: complete Python program

Slice From the Start

Skip the start index and the slice begins with the very first character.

Example

Take everything from the beginning up to position 5, which is left out:

Prompt
Write a Python program that slices a string from the start to position 5 (not included) and prints the result.
Output: complete Python program

Slice To the End

Skip the end index and the slice runs through the last character.

Example

Take everything from position 2 through the final character:

Prompt
Write a Python program that slices a string from position 2 to the end and prints the result.
Output: complete Python program

Negative Indexing

A negative index counts back from the string's end, so a slice can start there.

Example

Slice from position -5 up to position -2, which is left out:

Prompt
Write a Python program that uses negative indexes to slice a string from position -5 to position -2 and prints the result.
Output: complete Python program