A piece or subset or substring of a string is known as slice. Slice operator is applied to a string with the use of square brace [ ]. Operator [m:n] will give a substring which consists of letters between m and n indices, including letter at index m but excluding that at n, i.e. letter from mth index to (n-1)th index.
Simillarly, Operator [m:n:s] will give a substring which consist of letters from mth index to (n-1)th index, where s is called the step value, i.e. after at m, that at m+s will included, then m+2s, m+3s,..etc.
1. String Slicing Operator [start:End] i.e. [m:n]
s="Hello Python"
print(s[0:4])
#Output
Hell
s="Hello Python"
print(s[6:12])
#Output
Python
In the above example, you can see that in the first case the slice is [0:4], which means that it will take the 0th element and will extend to the 3rd element, while excluding the 4th element. Simillarly in the second case where slice is [6:12], it will consider the 6th element and extend to th 11th element.
2. String Slicing with Step Size [ m:n:s]
s="abcdefghijklmnop"
print(s[1:8:3])
#Output
beh
s="abcdefghijklmnop"
print(s[1:8:2])
#Output
bdfh
3. String Slicing with Index [ : n] or [m:n]
Now if we do not give any value for the index before the colon, i.e. m, then the slice will start from the first element of the string. Simillarly, if we do not provide any value for the index after the colon, i.e. n, then the slice wil extend to the end of the string.
s="Python"
print( s[ : 4] )
#Output
Pyth
s="Python"
print( s [ 4 : ] )
#Output
on
4. String Slicing with Index [ : ]
Simillarly, if we do not give any value at both the side of the colon, i.e. value for m and n are not given then it will print the whole string.
s="Python"
print( s[ : ])
#Output
Python
Now, if the second index is smaller than the first index then output will be an empty string represented by two single quotes.
s="Python"
print( s[ 4 : 3 ] )
#Output
' '
5. String Slicing with Index [ : : -1]
Now if we give the value of step as -1 and no value for m and n then it will print the string in reverse order.
s="Python"
print(s[ : :-1])
#Output
nohtyP
Lab Assignment:
1. Write a Python program to perform operations on word “governmentcollege”, extract second letter, extract first four letters and extract last six letters.
s="governmentcollege"
print("Second Letter is : ",s[1])
print("First Four Letters : ",s[0:4])
print("First Four Letters : ",s[:4])
print("last six Letters : ",s[-6:])
#Output
Second Letter is : o
First Four Letters : gove
First Four Letters : gove
last six Letters : ollege
2. Write a program to check whether a string is a palindrome or not.
s1=input("Enter String : ")
s2=s1[::-1]
if(s1==s2):
print("Palindrome !")
else:
print("Not a Palindrome!")
#Output
Enter String : radar
Palindrome !