Skip to main content

Slicing in Python

 

* Let's first understand how a slicing is been done--

Consider a string namely==>>

string = 'python_developer!'


If we print this then--

Output: python_developer!


>> Now lets do some slicing here--

print(string[0:17:2])


>> Then the--

# Output: pto_eeoe!


>> Lets see how it works--

So basically the print statement is in the form of 

print(string[a:b:c])


>>  Now here --

        a: Starting position

b: Ending position

c: Steps taken


>> If we take out length of the given string then--

print(len(string))

# Output: 17


* The total length of the given string is 17.

Therefore in our given problem the string will be printed from 0 index to 16 index and would take 2 steps.


>> Hence the output--

# Output: pto_eeoe!


>> Now the print statement that we have used here is--

print(string[0:17:2])


>> We can also use--

print(string[:17:2])


>> It will give the same output--

# Output: pto eeoe!


>> But what if we don't specify 17--

print(string[0::2])


* Its one and the same.

Because when we don't take 17 there then the index will end with the highest index value (i.e 17) taking 2 steps.


>> Lets try out some more slicing examples with the given string.

1) print(string[2:14:3])

# Output: tnel


2) print(string[6:13])

# Output:_develo


3) print(string[5::2])

# Output: ndvlpr


>> Now lets try negative indexing/slicing--

print(string[0:-4])

# Output: python_develo


* Here the starting position is 0 but the end position is -4.

Therefore, it will print the string excluding the last 4 characters from the string.


Note: The steps can have negative values(i.e we can write print(string[16:7:-2]) only if the starting position/index is greater than the ending position/index.


* For example:--

string = 'python_developer!'

print(string[13:7:-1])


>> Then the--

# Output: poleve

Comments