educative.io

String Slicing - Learn Python from Scratch

I am stuck on reverse slicing can any body help me

I don’t understand the output it is giving

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

.

I also am stuck on the quiz results for question 1 on the python lesson…
It asks

my_string = "0123456789"
print(my_string[-2: -6: -2])

what will be the outcome?
answer is 86 and im not sure how it came up with this… can anyone break it down for me?

So what you want to do first is understand the start and the end index.

  • -2 would mean 8 (10 - 2)

  • -6 would be 4 (10 - 6)

The range is then index 4 to 8. Since the step is in reverse (negative), we’ll go from 8 to 4 (4 not included since it is the end). So the range is [8, 7, 6, 5].

8th place is 8 so that is part of the slice. Go 2 steps back and we’re at the 6th position. 6 is the number there, and that becomes part of the slice. Go 2 steps back again and we’re at the 4th index. However, the end index isn’t included in the range. So we can’t make it part of the slice. We’re left with “86”.

P.S.
If we tried my_string[-2: -7: -2], the answer would be “864” because the 4th index gets included in this range.

2 Likes