Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!
To use the `slice()` method in Python, we first need to understand its syntax. The syntax for the `slice()` method is as follows:
Here, `string_name` is the name of the string from which we want to extract a part, `start_index` is the index from where we want to start extracting the string, and `end_index` is the index till where we want to extract the string.
Let’s take an example to understand this better. Suppose we have a string called `my_string` which contains the value “Hello, World!”. If we want to extract the word “World” from this string, we can use the `slice()` method as follows:
This will return the string “World” as it starts from index 7 and ends at index 12.
We can also use negative indexing with the `slice()` method. Negative indexing starts from the end of the string, where -1 is the index of the last character. For example, if we want to extract the last 5 characters from the string “Hello, World!”, we can use the `slice()` method as follows:
This will return the string “World!” as it starts from the second last character and goes till the end of the string.