String Slicing in Python

In this class, we discuss string slicing in python.

For Complete YouTube Video: Click Here

String Slicing

Slicing means taking a part of the string.

Before going to the concept of slicing. We should have some basics on how memory is assigned to strings. Click here.

Take some examples and understand slicing.

string=” hello learning monkey.”

strlength=len(string)

print(string[0:9:2])

In the print statement, we mentioned starting address, ending address, and jump.

Jump is taken 2. means increment position by 2.

Display character in position zero. Then leave the index position one. and take the character from position 2.

The above example displays hlola.

print(string[0::2]) here ending position is not given.

Default it will take till the end of the string.

print(string[::2]) here in this example, both starting and ending positions are not given.

The default will consider from start to end.

The example given below is important to understand.

print(string[::-1]). In this statement negative step count is given.

The starting and ending index is not given.

This will take the string in reverse order.

negative step count means take characters in reverse.

print(string[strlength::-1]) will display the string in reverse. because starting position is given as the length of the string.

print(string[-1:-8:-2]) will display yko.

When we are giving negative indexing, it’s essential to note starting index is -1.

From -1 to -8 with a step count of 2.

print(string[-8:-1]) will display g monke.

In this example, default positive step count. So take characters, not in reverse.