Akhand Chaurasia
Akhand Chaurasia

Reputation: 45

What is this behaviour of slicing in python?

What happens when we give string[::-1] in python such that the string gets reversed we know that by default the places are acquired by the 0 index and the last index+1 of the string or the -last index and -1 then how on writing above it starts counting from last index whether neither -1 is present at the first place nor the last index so that it starts decreasing 1 from where I can get depth knowledge of working of slicing in python and what does it return like stuff

Upvotes: 3

Views: 380

Answers (2)

JayantDwivedi
JayantDwivedi

Reputation: 31

Actually in case of python string slicing it takes three arguments:

[firstArgument:secondArgument:thirdArgument]

FirstArgument consists in the integer value from where the string get sliced.

SecondArgument tells about the up to where the string being sliced.

ThirdArgument tells about that how much step it get jumped

Example:

a="Hello"
print(a[::2])
# outputs 'hlo' without quoting.

Upvotes: 0

Ted Brownlow
Ted Brownlow

Reputation: 1116

From the python documentation on slicing sequences like [i:j:k]

The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced to len(s) if they are greater. When k is negative, i and j are reduced to len(s) - 1 if they are greater. If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

https://docs.python.org/3/library/stdtypes.html#common-sequence-operations

Upvotes: 3

Related Questions