Home > Blockchain >  Detailed explanation on how to know what the output will be when slicing and reversing a string in P
Detailed explanation on how to know what the output will be when slicing and reversing a string in P

Time:04-24

a="qwerty"

And I want the output to be "tre". But whenever I try doing

print(a[2:5:-1])
print(a[-4:-1:-1])
print(a[2:-1:-1])
print(a[-4:5:-1])

It all gives me blank spaces. But when I try

print(a[-2:-5:-1])

It magically outputs what I need.

So here's the question: Why didn't it work all those time, but did when I sliced it like this [-2:-5:-1]? Even though, as I think, I sliced and reversed the same piece of string. Explanation in details is needed.

CodePudding user response:

This because of the way stepping works in python. When you type my_list[start:end:step] python will interpret this as follows:

start from start index to end index value (not including end index itself) and each step should be step value.

For example consider the example below:

my_str = 'abcdefghijk'

print(my_str[2:7:2])

This code will give you ceg as output. Why? Because it moves from index number 2 to 7 not including 7 index itself. So it is 'cdefg'. Then get them with 2 steps meaning first c then increase the index by 2 (index=4) so gets to e (skips the d value).

But you need to know how reverse index works with stepping that I explained below.

Reverse stepping

What happens if the stepping value is negative. It starts from the start and move to the end number by -1 stepping value meaning that it moves backwards step by step.

But notice that it moves backwards to reach the end index. So the start value should be after the end in the list because it wants to move backwards from the start index to the end index. ([..., end, ...<---..., start, ...])

The reason of the output you asked

So when you typed print(a[-4:-1:-1]) python starts from -4 and each time moves one step backward to reach index -1 but it never happens as index -1 is after index number -4 and not before that. So python can't get the string so it returns -1. Same happens for the other examples.

But when you typed print(a[-2:-5:-1]) python starts from index -2 and move backwards step by step (-2 -> -3 -> -4) so it gets to index -5 and it stops and returns the value.

If you have any questions please ask.

CodePudding user response:

As listed in the docs:

s[i:j:k] slice of s from i to j with step k

With the resulting list being: [s[i], s[i k], ..., s[j]

  • Related