String Slicing Python
Slicing refers to extracting some words from a string. As in many other languages there are many different concepts for extracting a letters or words from a string ,in python we are having the concept of slicing. We can also the same things using looping, we will learn about it in our next tutorials.
Indexing in Strings
Before starting slicing, we need to understand the indexing in python. We have the concept of positive indexing and negative indexing.
Positive indexing starts from 0 to (length of string).It goes from forward to backward.
Negative indexing starts from -1 to -(length of string + 1).
It is illustrated in below example
Below are some examples of how to use string slicing to extract characters from string.
Accessing the characters in a string using positive index
eg.
string="We are studying string slicing" s=string[0] # A single character will be printed present at index 0 w=string[4] # A single character will be printed present at index 4 q=string[6]# A space is being stored in q as space is stored at index 6 print(s) print(q) # A single space will be printedprint(w)
Output:
W
r
Accessing the characters in a string using negative index
eg.
string="We are studying string slicing"
s=string[-1] # Last character from the string will be printed
w=string[-5] # -5 index is equivalent to 25
t=string[25]
print(s)
print(w)
print(t)
Output:
g
i
i
Slicing
We can extract the range of characters from string by providing indices in square brackets as [x:y:z]
where,
x= Starting Index (from where you want to extract)
y= Ending Index(upto where you want to extract)
z= Jump(Number of characters you want to jump)
Note: Always keep one thing in mind that characters are printed from index x to y-1
We will understand the following with the help of examples:
eg.
string="We do great things here"
s=string[0:5]
w=string[-4:-1]
t=string[6:-5]
print(s)
print(w)
print(t)
Output:
We do
her
great things
eg.
string="We do great things here" s=string[0:5:2] t=string[6:-5:3] print(s) print(t)
Output:
W o
gatn
Here we are seeing that string skips number of positions that is given in z position i.e
s will print characters at 0,2 and 4 index
t will print characters at 6,9,12 and 15 index
Slicing without some parameters
eg.
string="We do great things here" s=string[0::2] m=string[::] p=string[1:] q=string[:7] t=string[:-5:3] print(s) print(m) print(p) print(q) print(t)
Output:
W ogettig ee
We do great things here
e do great things here
We do g
Wdgatn
Here we see that string slicing also work when no arguments are given.It automatically takes whole string if no arguments are given.
Comments
Post a Comment
Please do not enter any spam link in the comment box