Slices in Python can be used where only a portion of a string or list is required. This is particularly advantageous where a string or list is very large. When using slices, three optional values can be specified, a start position, a stop position and a step value. Below is an example of a slice that returns a portion of a string, where a start and stop value is specified in square brackets, separated by a colon.
stringexample = "This is a string" print(stringexample[1:6])
A few things to note about slices are that, firstly, they are zero based, so the ‘T’ in the above example is at position zero and not one, and secondly, the portion extracted goes up to but not including the stop value. The above example would display the following.
It isn’t absolutely necessary to specify both a start and stop value for the slice. Where no start value is specified, the slice starts from the first position in the string or list. Similarly, where no stop value is specified, the slice goes right to the end.
The first example above goes from the start of the string up to, but not including, a stop value of six, whilst the second example goes from a start value of six to the end of the string.
This i s a string
If it is not required to return every value in a string or list, but instead, for example, return every other value, then the third optional step value can be included. Here, the above examples have been repeated, but with a step value of two to return every other character in the string.
The resulting output is as follows.
If every other value of the whole string is required in the output, this can be achieved by not specifying either a start or stop value.
Replacing items in a list is accomplished in a similar fashion to assigning values to the list initially, except the slice values are specified in square brackets. Here the names ‘Fred’ and ‘Tom’ are replaced with ‘Frieda’, ‘John’ and ‘James’.
names = ["Andrew", "George", "Bob", "Fred", "Tom", "David"] names[3:5] = ["Frieda", "John", "James"]
The full list now looks like this.
['Andrew', 'George', 'Bob', 'Frieda', 'John', 'James', 'David']