Introduction to String Indexes and Slicing
In this lesson you will how to extract specific parts of a string using indexes and string slicing.
Here, we declare the following variable:
Let's say we want to print only the first character of our string. To do that, we have to talk about indexes.
When working with strings, each character within the string has a specific position called index.
In Python, the first character of a string has index 0, the second character has index 1, an so on...
Knowing this, we can use index 0 and the square bracket notation to extract the first character from our string:
Now, let's print the second character of our string. Since we start counting at 0, the second character has index 1:
Note that each character in the string has its own index, including whitespaces. Therefore, text[5]
is just a blank space.
What will be the output?
What will be the output?
We can also extract a range of characters from a string using the so called slice syntax 'string'[start:end]
. For example:
So, what happened here? By executing text[1:3]
, we extracted a range of text starting from index 1 (included) to index 3 (excluded).
Let's extract the word Hello from our text:
What will be the output?
What will be the output?
When using the slice syntax 'string'[start:end]
, the start index has a default value of 0.
Hence, if we do not include a number before the colon, the extracted range starts at index 0. For example:
The default value of the end index always equals the number of characters of the entire string, in other words the index of the last character plus 1.
Hence, if we do not include a number after the colon, the extracted range ends with the last character. For example:
If we don't include a start or end index, we get a copy of the entire string:
What will be the output?
What will be the output?
Last but not least, you can also include negative numbers when working with indexes. Negative numbers allow you to start counting from the end of a string.
For example, with -1 you can extract the last character of a string:
-2 represents the second last character of a string, an so on:
This also works with the slice syntax:
What will be the output?