In this tutorial, I will explain to you the concept of Python Slice operator in as easy as possible language. But first, let me tell you how it all started –
A few Days back I posted this story on my Instagram asking you guys – How many lines of code do we need to write in order to print a Python String in reverse order.
Whereas few of you answered correctly however many of you didn’t. Therefore, I decided to do a detailed tutorial on this topic.
Furthermore if you don’t want to miss all such fun and informative stories, then come and join me on my Instagram. Here are the links.
My Private Instagram, here and RebellionRider.com official Instagram handle here.
How to reverse Python string?
Those of you who are here to learn how to reverse a Python string then I won’t keep you waiting. Here you go –
It takes just one LOC to reverse a Python string.
Usually, if you are using the interactive mode of Python Programming, then you can reverse a string in just a single line. Like this—
“Hi, I’m a string” [: : -1]
Thus, on execution the string “Hi, I’m a string”, will be printed in reverse order like this—
And if you love writing a neat and clean code which is much easier to read; then we can modify the above program. However, that will take two line of codes (LOCs). Like this –
Str = “Hi, I’m a string” print(str [::-1])
Just like that! That’s how we reverse a string in Python Programming. If you only wanted to learn that then I just showed you the entire process of reversing a Python string. But, if you want to learn the concept to nail your interview then keep reading.
In order to better understand the concepts of Python Slice operator we first need to know what is indexing and how it works. Let’s quickly learn that.
There are two types of Indexing in Python Programming. These are –
- Simple Positional Indexing and
Simple Positional Indexing
The python interpreter saves all the characters of the string in a sequential manner and assigns them index numbers. Moreover, the index numbers start with 0. This means the first character of the string will be saved at index 0. And the second character will be saved at index 1, and so on.
That is something we all know. But did you also know that –
Python interpreter not only assigns positive index numbers to the string but also assigns negative index numbers. In fact, this is highly unlikely in other programming languages. The negative index number starts with -1 and the numbering starts from the end of the string. Meaning the last character of the string will be assigned index number -1 and so on.
This process of sequential indexing of the string (whether it’s positive or negative) is called “Simple Positional Indexing”.
The second type of indexing is “Slicing”. Slicing is a process of extracting a substring from the main string in just one single step.
Consequently, using Python Slicing technique you can extract a range of indexes by just writing a single line of code. Moreover, there is no need to write any conditional control or loop statement.
There are two ways to slice a string in Python Programming. These are:
- Either by using Python Slice operator
- Or by using Python Slice function
In this tutorial, we will focus on learning the concepts of Python Slice using Python Slice operator.
The Syntax of Python Slice Operator
The syntax of Python slice operator is fairly simple.
This operator has three flags. These are –
- “start” – it indicates the index number from where the slicing will start.
- “stop” – it implies the index number where the slicing will stop.
- “step” – it indicates the number of hops interpreter will take to slice the string.
Things you must take care of while using Python Slice operator.
- Each of these flags is separated by colons (:).
- All the flags must be enclosed inside a pair of square brackets ( [ ] ).
- Every Flag is an integer flag which means they accept only integer values.
- Each of these flags is optional. None of them is mandatory.
Because all these flags are optional thus you are free to skip any of them. In case you skip any flag then the Python interpreter will use their default values. The default values for the flags are –
- Start – 0 (The starting index of the string)
- Stop – last index number of the string
- Steps – 1
Now, if you ask, the weird looking contraption, where some integer values are separated by colons enclosed inside a pair of square brackets, is known as Python Slice operator.
Examples of Python Slice Operator
In this section, I will try to demonstrate some valid and legit ways to use Python slice operator. By using some easy to understand example. Furthermore, I will do multiple examples to show you the use of each of the flag of the Python Slice operator.
For the demonstration, I will use our favorite string “What’s Up Internet!”.
Example 1: Python Slice Operator – start
In the first example, I will show you the use of the first flag of the Python slice operator.
Let’s say I don’t want to print this entire string, rather just want to display the word “internet”.
str = "What's up internet!" [10::] print (str)
Here’s what I have done. I have put the slice operator right after the string. That also in the same line where I have declared and initialized our variable. In that slice operator I have specified only one value which is 10.
In the next tutorial we have discussed why I don’t recommend putting slice operator with the variable declaration. Don’t forget to read that after this one.
10 is the index number from where the word “internet” is starting. I have counted that already, if you want you can do that too.
If you will look carefully then you will find out that I have only used the first flag “start” of Python Slice operator. I have specified 10 as its value. Followed by that I have only put the colons not any values. Which indicates to the interpreter that I have not specified any value for second (stop) and third flag (steps).
As I said earlier that when you do not specify any value for these flags then the Python interpreter will use their default values. The default value for the second flag “Stop” is the last index of the string. And, for the third flag “Steps” is 1.
On execution the interpreter will print the sub-string from index 10 to the last.
Example 2: Python Slice Operator – start : stop
In the second example, I will demonstrate how to get more control over your string using the first two flags of Python slice operator.
Now suppose instead of the entire string I just want to print only the phrase “What’s Up”. Let’s see if we can do that.
str = "What's up internet!" [0:9:] print (str)
This time I am using the first two flags of the operator – the start and the stop. Here I have specified 0 as the value of the start flag and 9 as the value of the stop flag.
On execution, the interpreter will slice the string and return a substring from index 0 up to but not including index 9.
Example 3: Python Slice Operator – start : stop : steps
In the third example, I will demonstrate how to use all three flags of the Python Slice operator. Using the third flag “steps” you can tell your interpreter how many hops it should take while slicing the substring.
For example, if you set steps to 2 then the interpreter will select and return every second item from the string starting from index 0.
Let’s say I want to select every second character of this entire string. For that, the code will be—
str = "What's up internet!" [0:19:2] print (str)
On successful execution, the interpreter will return a sub-string containing every second item from index 0 to index 19.
If you are like me who learns better by watching Videos then you can enjoy this video tutorial here
In this Python tutorial we focused only on the positive positional indexing. But in the next one I will tell you why I put the Python Slice operator in the same line where I declared and initialized the variable.
There we will also unfold the mystery behind the changing behavior of slice operator on using negative positional indexes.
Stay tuned. Thanks, and have a great day.