Python For GCSE
Slicing Strings & Lists
Slicing is a Python-specific technique that we can use to extract sublists or substrings from lists or strings. Whilst you aren't going to get questions requiring it in a GCSE examination, the techniques are useful for writing programs that need you to manipulate a string or list.
From ... To
The following example takes a slice from the string. It starts at position 3 and stops before it reaches position 6. That is, it reads 3 characters at positions 3,4,5.
name = "Ozymandias" s = name[3:6] print(s)
From ... To ... Step
If we add a third argument, it will be used as a step. The following starts at the second character and reads every other character through the rest of the string.
name = "Ozymandias" s = name[1:10:2] print(s)
The general format we are using is,
[start:stop:step]
Leaving Out The First Argument
If we omit the first argument, the slice starts from the beginning of the string.
name = "Ozymandias" s = name[:3] print(s)
Leaving Out The Second Argument
If we omit the second argument, the slice goes from wherever we choose to start right to the end of the string.
name = "Ozymandias" s = name[3:] print(s)
Negative Stop
If the stop value is negative, the slice stops that many characters from the end of string.
name = "Ozymandias" s = name[:-4] print(s)
Negative Start
If the start value is negative, we start that many characters from the end of the string or list.
name = "Ozymandias" s = name[-4:] print(s)
Negative Step
If the step is negative, we read the string or list backwards. The following reverses the string or list.
name = "Ozymandias" s = name[::-1] print(s)