In the Indexing Strings for Python tutorial, we reviewed how to access data placed in the form of strings. Because we know how to locate by indexing, it would be beneficial to delve deeper and explore how to manipulate the data using indices.
One of the most helpful python functions to use for strings is the slice( )
function. This function allows the program to access one or more characters in sequential order. The programmer can specify the beginning and end points by using the following syntax:
slice(start, end, step)
When the slice function is initiated, Python will automatically default the start position to zero unless it is told otherwise. Because of this, start is optional. The next parameter is end, which should be the index value of where you want the program to stop slicing. Note, that the program will end counting just before the index indicated.
Take a look at the code below to see how using either 0
as a parameter or leaving it blank will yield the same result.
If you look at the output for both functions, you’ll see that you have the same result. This is because the program will assume it should start slicing at the zeroth index if no start parameter is indicated.
You’ll also notice that each function only prints "alpha", "beta", "gamma"
because the slicing stops at the index before the end parameter. So, while the index of “delta” is 3, it will not print.
The step parameter is used to tell the program how many places to count before slicing again. This is optional and can be helpful when you have a set number of places that you want to skip in a list.
In the example below, let’s say you want the program to count and print every other pastel color, starting at the zeroth index.
In this tutorial, we took a closer look at how to access specific items in a list using the slice ( )
function. We know how to use the start, end, and step parameters to tell the program what and how to access certain strings within a list. Now that you are aware of the basics, take a few minutes to solidify your comprehension by reviewing the Vocabulary List and completing the Challenge Scenario below.
Review the following terms and try to define on your own.
Review the program below and complete the following prompts.