DEV Community

Dani
Dani

Posted on • Updated on

Slicing in Python

Learning a new programming language can seem like a daunting task. As overwhelming as it may seem; the more you learn, you will start to see similarities, and common types of practices that traverse multiple languages. One of these similarities include the idea of "slicing" some form of data.
Slicing does exactly what it implies, it "slices" up data into smaller parts. Every language has their own particular way of doing this. Lets take a look at how Python in particular handles this kind of operation.
First let's start with making two different variables, one a string, the other a list.

my_string = "Hello, I am a string!"
my_list= ["A0","B1","C2","D3","E4","F5"]

There is a different character at each index. If we wanted to call up that character we could write something like this, using a square bracket

print(my_string[3])
#output would be "l" as l is in the third index of the string. 
print(my_list[0])
#output would be "A0" as "D3" is the first index in the list, and index count starts as 0 

If we wanted to start slicing things up, all we need to add is a simple colon ":". The colon will indicate a starting point. It will output the data starting at that point. If you don't add a number after the colon it will automatically print the rest of the length

my_string = "Hello, I am a string!"
my_list= ["A0","B1","C2","D3","E4","F5"]

string_splice = my_string[3]
list_splice = my_list[0]

print(string_splice)
#output would be "lo, I am a string!"
print(list_splice)
#output would be "['A0', 'B1', 'C2', 'D3', 'E4', 'F5']"

If you were to add a number after the colon you would be giving it an end point, for example

my_string = "Hello, I am a string!"
my_list= ["A0","B1","C2","D3","E4","F5"]

string_splice = my_string[3:8]
list_splice = my_list[0:3]

print(string_splice)
#output would be "lo, I"
print(list_splice)
#output would be "['A0', 'B1', 'C2']"

for my list_splice we are essentially saying start at the 0 index, then move 3 spaces forward and stop. we have just successfully sliced our data
But we aren't done yet! A third number can be added, called the step.

my_string = "Hello, I am a string!"
my_list= ["A0","B1","C2","D3","E4","F5"]

string_splice = my_string[0::2]
list_splice = my_list[0::2]

print(string_splice)
#output would be "Hlo  masrn!"
print(list_splice)
#output would be "['A0', 'C2', 'E4']"

the step will essentially say, start at an index:end at this index:take this step through out

and there you have it. A way to slice data in python.

Top comments (0)