Question 6
The following Python expression is entered into a fresh Python shell with no prior import statements. Determine the result from evaluating the following expression. [3 marks]
Solution
String slicing: [start:stop:step]
start: include character from this index onwardsstop: exclude character from this index onwardsstep: advance by how many places at once (negative values means advancing backwards)
'cucumbernimbus'[-1::-1] means we begin from the last index (since we are dealing with a negative index here as the start value).
Since the stop value is not specified here, we can assume that we want to iterate through the whole string.
We can probably assume that it is fixed to the last index as well by default, since cucumbernimbus[:] will automatically set the start and stop values at the start and tail end of the string by default.
This would mean that 'cucumbernimbus[-1:] would output an empty string, because from the last index to before the last index does not capture any characters in between.
However, since we also have a step value defined as -1, this permits counting backwards from the last index to the first one.
Effectively, cucumbernimbus[-1::-1] reverses the whole string inside out.