String Slicing
Get familiar with string slicing in Python, including basic slicing, slicing with a step, reverse slicing, partial slicing, and slicing by character.
The technique of extracting a portion of a string by utilizing its indices is called slicing. Several real-world applications use slicing. For example, slicing can be used to extract the required information from messages sent over a communication because they conform to a specific format. Several data processing and cleaning tasks like web scraping, tokenization, and feature extraction also benefit from slicing.
Slicing in Python
For a given string, we can use the following template to slice it and retrieve a substring:
string[start:end]
The
start
index indicates where we want the substring to begin.The
end
index specifies where we want the substring to terminate. The character at theend
index will not be included in the substring obtained through this method.
Here’s an example illustrating the use of the slicing:
my_string = "This is MY string!"print(my_string[0:4])print(my_string[1:7])print(my_string[8:len(my_string)])
Explanation
Here’s the code explanation:
Line 2: This expression extracts a substring from
my_string
starting from the index0
(inclusive) up to, but not including, the index4
. So it printsThis
, which are the characters at indices0
,1
,2
, and3
.Line 3: This expression extracts a substring from
my_string
starting from the index1
(inclusive) up to, but not including, the index7
. So it printshis is
, which are the characters at indices1
,2
,3
,4
,5
, and6
.Line 4: This expression extracts a substring from
my_string
starting from the index8
(inclusive) until the end of the string. Thelen(my_string)
function returns the length of the string, ensuring that it captures all characters until the end. So it printsMY
...