liveBook · Manning

Slicing

As explained in Get Programming: Learn to code with Python

Slicing selects or partitions a portion of an indexed sequence or multidimensional array, often along specified indices or dimensions.

Slicing selects a substring from a string using square brackets and colon-separated indices. In [start:stop:step], start is included, stop is excluded, and step sets how many characters to skip. Positive steps move left to right; negative steps move right to left. section 7.2

[start_index:stop_index:step]

Use this syntax pattern to see how start, stop, and step fit together. section 7.2

Separate a first and last name

For “Aqua Man,” find the space, then slice from the start to the space for “Aqua” and from just after the space to the end for “Man.” section 12.2

Listing 12.2. Storing the first and last names in variables
space = name1.find(" ")                              #1
name1_first = name1[0:space]                         #2
name1_last = name1[space+1:len(name1)]               #3
space = name2.find(" ")                              #4
name2_first = name2[0:space]                         #4
name2_last = name2[space+1:len(name2)]               #4

See the assignments that find the space and store each name using slices. section 12.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines start, stop, and step, explains excluded stop bounds and step direction, and applies slicing to split names.
Examples
Uses student records, character groups in “snap crackle pop,” and first- and last-name extraction.
What it assumes
Builds on string indexing and index positions while explaining slicing notation and bounds.
What you can do after
Apply slicing to extract substrings and separate first and last names.
How it connects
Connects slicing with strings, string indexing, and the find operation.

Also explained in

Compare how 16 books explain slicing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.