Hello friends and welcome to geeksforgeeks,
in this tutorial we will learn about slicing and splitting in python. So, let’s move
to geeksforgeeks IDE to learn about them. Let’s first learn slicing. Slicing can be
done on lists, strings and tuples. Slicing in python can be done in this format, List1[start:end:step]
By writing this, we get values from index start to end – 1 with an index difference
equal to step. Let’s see this code, we have a list and we are slicing it from index 1
to 4 with a step equal to 1. Let’s run this code, we can see that all
the values form index 1 to 4 of the list l are printed.
If we are using a positive value of step, then the default value of start and end is
the starting and ending index of the list respectively. Whereas, if we are using a negative
value of step, then the default values of start and end is the ending index and starting
index of the list that is, just the opposite as in the case of positive step.
Let’s look at this example, here we are using this property to print a list in reverse.
By writing this, we mean start=4, end=0 and step=-1. Let’s run
this code. We can see that reverse of the list is printed.
Now, let’s learn splitting a string in python. To split a string we use split function.
This is generally used when we have a string containing the elements separated by a character.
It could be a comma, space or anything. Suppose we have a string like this and we wish to
all all the names of fruits in a list. So, str is a string containing the names of
fruits separated by a comma, to get these into a list we write, str.split and within
brackets a comma and assign it to a list variable. Let’s run program, we can see that all the
elements are now in a list Let’s look at another example, here we have
3 values separated by a space. To get these values into 3 different variables, we write,
a comma b comma c=str.split(). If we do not have anything in the argument of split,
it takes space as default. So, in this tutorial, we discussed splitting
and slicing. We will continue learning python in the coming tutorials, thank you for watching!
Please leave us your likes and comments in the comments section