Define Substrings
In this step, you will learn how to define substrings in Python. A substring is a contiguous sequence of characters within a string. Understanding how to work with substrings is essential for many string manipulation tasks.
Let's start by creating a Python script called substrings.py
in your ~/project
directory. You can use the VS Code editor to create this file.
## ~/project/substrings.py
string = "Hello, LabEx!"
This script initializes a string variable named string
with the value "Hello, LabEx!"
.
Now, let's add some code to extract substrings from this string. A simple way to define a substring is by using slicing. Slicing allows you to extract a portion of a string by specifying the start and end indices.
Add the following lines to your substrings.py
file:
## ~/project/substrings.py
string = "Hello, LabEx!"
substring1 = string[0:5] ## Characters from index 0 to 4
substring2 = string[7:12] ## Characters from index 7 to 11
print(substring1)
print(substring2)
In this example, substring1
will contain the characters from index 0 up to (but not including) index 5, which is "Hello"
. substring2
will contain the characters from index 7 up to (but not including) index 12, which is "LabEx"
.
To run the script, open your terminal in VS Code and execute the following command:
python ~/project/substrings.py
You should see the following output:
Hello
LabEx
You can also use negative indices to define substrings. Negative indices count from the end of the string. For example, string[-1]
refers to the last character of the string.
Modify your substrings.py
file to include the following:
## ~/project/substrings.py
string = "Hello, LabEx!"
substring1 = string[0:5] ## Characters from index 0 to 4
substring2 = string[7:12] ## Characters from index 7 to 11
substring3 = string[-1] ## Last character
print(substring1)
print(substring2)
print(substring3)
Now, run the script again:
python ~/project/substrings.py
The output should now include the last character of the string:
Hello
LabEx
!
Understanding how to define substrings using slicing is a fundamental skill in Python. Experiment with different start and end indices to extract various parts of the string.