Python Basics
Theory: String cuts
When we work with strings in programming, we regularly have to extract parts of them.
For example, we need to find a smaller string inside a larger one. In this lesson, we'll look at how to do it.
Substrings and slices for strings
A substring is part of a string that needs to be found and extracted.
Suppose we have a date in this format: 12-08-2034. We need to extract a substring from it that only has the year.
If you think about it logically, you have to calculate the index from the first character of the year and extract the four characters. The indices in the string start with zero, so the first character of the year is available at index 6, and the last character is at index 9. Let's check it out:
Now we know these indices, we can use slices and get the desired substring:
In Python, string slices are a mechanism by which we extract a substring according to specified parameters. In the example above, we took a substring from index 6 up to but not including index 10, meaning from 6 to 9 inclusive. The formula looks like this:
Slices are a tool with many variations. For example, if we don't specify a second boundary, we extract all the characters up to the end of the string. It applies to the first boundary, meaning the beginning of the line:
You can even specify negative indices. In this case, it starts from the opposite side:
Slices have two mandatory parameters, but sometimes we can use a third one.
Extraction steps
Slices have a third optional parameter, extraction step. It's 1 by default, but we can change it:
All of these can be combined with open boundaries, in other words, without setting a beginning or end:
The step can be negative. In this case, we work with it from the end. From this comes the most popular way to use the extraction step; to reverse the string:
If we use a negative step and extract the slice elements in reverse order, we should also specify the slice boundaries in reverse order. We indicate at first the right slice boundary and then the left one:
The slices can be specified using variables as well as numbers:
As you can see, slices do a lot. Don't worry if you don't remember all these combinations right now. Later, you'll learn how to use them without looking at the documentation.
Completed
0 / 43