educative.io

String Slicing - Learn Python from Scratch


#1

I am stuck on reverse slicing can any body help me


#2

I don’t understand the output it is giving


#3

Dear Osaid
Here are my personal opinions for the example listed about reverse slicing:
We know the template for the string slicing is: string[start:end:step]
my_string=‘This is My string!’

In the first example my_string[13:2:-1],
13 means the 14th character in the string (from 0 to13), in this case the character is ‘r’,
2 is the third character (from 0 to 2) so we have to choose the 4th character ‘s’ because we cannot choose the end index in the substring
the step is -1, it means we need to reverse the string from right hand side to the left hand side and it should include each character with no skip.
therefore, it starts with 14th character ‘r’ and end at the 4th character ‘s’ with step -1, the final output is ‘rts yM si s’

in terms of the next one, it is actually the same, we start 18th character (from 0 to 17) ‘!’ and end at the 2nd index ‘h’, but the step is -2, indicating we should skip one character. the final output is ‘!nrsY ish’ (note: space is also one character)

the above is my opinion about the reverse silicing string. I hope it can help you a little bit!

Best wishes

.